AndyWarren
AndyWarren

Reputation: 2012

Table Row Odd/Even Reset

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?

Upvotes: 4

Views: 4908

Answers (3)

Blazemonger
Blazemonger

Reputation: 92913

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

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

http://jsfiddle.net/mblase75/xgQ8Q/

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

Upvotes: 11

Johnny5
Johnny5

Reputation: 6862

jQuery("table tr:nth-child(odd)").css("background-color", "red");
jQuery("table tr:nth-child(even)").css("background-color", "yellow");

http://jsfiddle.net/xgQ8Q/5/

Upvotes: 1

Selvakumar Arumugam
Selvakumar Arumugam

Reputation: 79830

Try using table in context like below,

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

Upvotes: 4

Related Questions