Get Even More Visitors To Your Blog, Upgrade To A Business Listing >>

Applying nth-child pseudo selector to a specific row class

Applying nth-child pseudo selector to a specific row class

Problem

I've got a bit of an issue that I'm unsure if it's a browser thing or a CSS3 thing.

I have a datagrid using a standard HTML table:


        ...
    
... ... ...
... ... ...
... ... ...

I have a jQuery function that is searching the contents of the TD elements. If it's found, it maintains the found Class. If it's not found, then it removes the found class and and adds a not-found class. Naturally, not-found just sets display: none

So the search function is working the way I'd like. Classes are being assigned appropriately. However, I'm using CSS pseudo selectors to apply styling to alternate rows.

tr.found:nth-child(even) {
    background: #fff;
}
tr.found:nth-child(odd) {
    background: #000;
}

This works out great before a search takes place. However, after a search and the not-found class is applied, the pseudo selector seems to apply only to the element rather than the element and the class. Either that, or the pseudo selectors are applied during page load and are left static at that point.

I could go through in my jQuery search and reassign specific even and odd classes, but that gets messy. It wouldn't be that big of a deal, but my column headers are sortable, so I'd have to reapply classes on that event as well creating kind of an inefficient method to do what I'm doing. If data samples get too large, you would likely be able to see the class changes iteratively, something I'm attempting to avoid.

Any solutions to this?

EDIT

As requested, I setup a JSFiddle so you geniuses can toy with it: http://jsfiddle.net/bDePR/

Searching for President or Secretary will yield the behavior.

Problem courtesy of: Brian

Solution

This is the simplest method I could come up with, use the jQuery :visible selector to find all the visible tr elements (after they have been sorted) then simply apply CSS to alternating ones!

// reset the background
$j('tr').css('background', '#ccc');
$j('tr:visible').each(function(i){
    if((i % 2) == 0) {
        // apply background to every other one
        $j(this).css('background', 'yellow');
    }
});

e.g. http://jsfiddle.net/bDePR/1/

Edit:

This, by @amustill does the same but is more efficient/concise

// reset the background
$j('tr').css('background', '#ccc');
$j('.found').filter(':odd').css({ background: 'yellow' });
Solution courtesy of: Matt Kieran

Discussion

View additional discussion.



This post first appeared on CSS3 Recipes - The Solution To All Your Style Problems, please read the originial post: here

Share the post

Applying nth-child pseudo selector to a specific row class

×

Subscribe to Css3 Recipes - The Solution To All Your Style Problems

Get updates delivered right to your inbox!

Thank you for your subscription

×