jQuery Table Striping Bug
I have been using jQuery to do table striping, and up until today, I have not had any problems with it.
I had just been using the :even and :odd selectors to add classes to each table row.
Here is the code that I have been using:
$(document).ready(function(){
$("table.striped tbody tr:odd").addClass("odd");
$("table.striped tbody tr:even").addClass("even");
});
Seems easy enough. Then I just styled the odd table rows like so:
table.striped tr.odd td { background-color: #f0f0f4; }
One thing to note is that the :even and :odd selectors are zero-indexed, so the first table row will have a class of even, and not odd. Here is an example showing this simple striping.
Multiple Striped Instances
The situation that I had today had two different tables that were being striped. So based on the code, you would think that there wouldn’t be a problem. Here is the example with two striped tables on the same page.
Weird, so it looks like the first table row in the second striped table has a class of even instead of odd. I thought that the client may not like that because the two tables were not consistent, so I tried to think of another way to do the striping.
The nth Child
So based on the documentation, it looks like the nth child selector would be the solution. I just modified my JavaScript like so:
$(document).ready(function(){
$("table.striped tbody tr:nth-child(odd)").addClass("odd");
$("table.striped tbody tr:nth-child(even)").addClass("even");
});
As a note, the nth child selector is not zero indexed, so the first table row will have a class of odd instead of even. Here is the fixed example.
Conclusion
From what I can tell, this does not appear to be a browser problem, but a bug in jQuery. I have checked this in Firefox, Safari, IE6 and IE7.