Reputation: 73
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:
<table>
<thead>
...
</thead>
<tbody>
<tr class="found">
<td>...</td>
<td>...</td>
<td>...</td>
</tr>
<tr class="found">
<td>...</td>
<td>...</td>
<td>...</td>
</tr>
<tr class="found">
<td>...</td>
<td>...</td>
<td>...</td>
</tr>
</tbody>
</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.
Upvotes: 7
Views: 1888
Reputation: 4220
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' });
Upvotes: 1