Take the 2-minute tour ×

I am using this:

jQuery("tr:odd").css("background-color", "#f5f5f5");
jQuery("tr:even").css("background-color", "#ececec");

Just simply adding a background color to alternating table rows, which works fine. The problem is that if there are multiple tables in the same page, it just keeps iterating down each table instead of resetting for each table and starting new. My th background color is the same color as my even rows So eventually it catches up and I have a th and tr that are the same color so it looks like one big row.

How can I use those two lines of jquery, but make it start over for each table on the page if there are multiple tables?

share|improve this question
Is there a particular reason you're doing this with jQuery, rather than pure CSS? –  cimmanon May 29 '13 at 19:10
Simply for cross browser compatibility. Didn't think nth-child was fully supported, especially in older versions of IE. Am I wrong about that? –  AndyWarren May 29 '13 at 19:15
IE9+ supports nth-child. jQuery has dropped support for anything older than IE9 in newer versions: jquery.com/browser-support –  cimmanon May 29 '13 at 19:22
FWIW, Modernizr doesn't have a detect for nth-child, but it does have a non-core detect for last-child, which is (probably) supported on the same browsers. You could use pure CSS for browsers that support it and a Modernizr detect to apply JS to browsers that don't. –  Blazemonger May 29 '13 at 20:28
add comment

3 Answers

up vote 6 down vote accepted

Start by selecting the tables, then finding the child rows:



Vega's answer uses the same approach with fewer characters.

share|improve this answer
Perfect. I'll accept as soon as it lets me, says 12 more minutes. –  AndyWarren May 29 '13 at 19:05
This still applies to all my tables. Can you just refer to a specific table using ID? –  Vippy Dec 13 '13 at 23:21
Figured it out, I could use an ID tag as such: jQuery("#myTable tr:odd").css("background-color", "#EFF3FB"); –  Vippy Dec 14 '13 at 3:44
add comment
jQuery("table tr:nth-child(odd)").css("background-color", "red");
jQuery("table tr:nth-child(even)").css("background-color", "yellow");


share|improve this answer
+1. Didn't occur to me that using :nth-child(odd) instead of :odd would give a different result. –  Blazemonger May 29 '13 at 20:23
add comment

Try using table in context like below,

jQuery("tr:odd", 'table').css("background-color", "#f5f5f5");
jQuery("tr:even", 'table').css("background-color", "#ececec");
share|improve this answer
Thanks for the quick answer. This worked as well, so I'll toss an upvote on it. Just happened to get Blazemonger's answer first. –  AndyWarren May 29 '13 at 19:10
@AndyWarren Agreed. –  Vega May 29 '13 at 19:12
add comment

Your Answer


