Reputation: 2205
I have 2 tables and would like alternating row colors to reset based on a new table. the tr:odd
seems to be applied across both of my tables.
Here's my table html:
<table class='myTable'>
<tr class='myRow'>
<td>row 1</td>
</tr>
<tr class='myRow'>
<td>row 2</td>
</tr>
<tr class='myRow'>
<td>row 3</td>
</tr>
</table>
<hr>
<table class='myTable'>
<tr class='myRow'>
<td>row 1</td>
</tr>
<tr class='myRow'>
<td>row 2</td>
</tr>
</table>
css:
.myAltRowClass { background: #DDDDDC; }
javascript:
$(".myTable .myRow:odd").addClass('myAltRowClass');
jsfiddle: http://jsfiddle.net/niner/Sgq9T/
The 1st table and 2nd table both have alternating colors, but the 1st row in table 2 should start out with the normal (white) color, and not the alternate (grey) color.
I would appreciate any help. Thanks.
Upvotes: 3
Views: 1286
Reputation: 283
Just to add to these: jQuery's :odd, :even, etc pseudo-class selectors DON'T behave the way you think they do; they look for e.g. the odd members of the jQuery array created by the preceding selector. You could think of $('.myTable .myRow:odd') as creating an intermediary array of objects based on $('.myTable .myRow') and then removing the even numbered elements from that array. Similar for :even, :first, and so on (although nth-child() is different and does do what you might expect).
Upvotes: 1
Reputation: 78691
You can use the CSS3 selector :nth-child(odd)
(or even
if that's what you need) which will work in jQuery too. Better than :odd
anyways, because that is not a natively supported selector and jQuery cannot use the more performant native querySelectorAll
for it (as described in the docs).
$(".myTable .myRow:nth-child(odd)")
.addClass('myAltRowClass');
Upvotes: 1
Reputation: 253318
Sure, just select the rows of each table
independantly:
$(".myTable").find('.myRow:odd').addClass('myAltRowClass');
Or, preferably, just use CSS:
table.myTable tr:nth-child(even) {
background: #DDDDDC;
}
Note that I've switched to even
in the CSS :nth-child()
example, this is because JavaScript is zero-based, whereas CSS is one-based.
Or by combining the two approaches together:
$('.myTable tr:nth-child(even)').addClass('myAltRowClass');
Upvotes: 7