I have the following two tables and jQuery:
<table class="grid" />
<table class="grid custom" />
$('.grid tr:even').addClass('alt');
What’s happening here is that both tables are being targeted by jQuery. The first table is fine as the even row is being selected, however the odd is being selected on the second table.
table 1 (grid)
row 1
row 2 – background color (this is right)
table 2 (grid custom)
row 1 – background color (this is wrong)
row 2
How can I fix this?
http://jsfiddle.net/Ftk5n/
The problem is that the
$('.grid tr:even')selector is applying the:evencriteria to the set of all rows returned by.grid tr. You want the:evento be applied on a per-table basis.Incidentally, you can do this purely in CSS: http://jsfiddle.net/ahf9q/1/
Edit: Turns out jQuery has the
nth-childselector that operates just like CSS does. If you’re set on doing this in jQuery rather than CSS, you could do:http://jsfiddle.net/Ftk5n/2/