Niner
Niner

Reputation: 2205

CSS alternating table row to reset in a new table?

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

Answers (3)

user2310967
user2310967

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

kapa
kapa

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');

jsFiddle Demo

Upvotes: 1

David Thomas
David Thomas

Reputation: 253318

Sure, just select the rows of each table independantly:

$(".myTable").find('.myRow:odd').addClass('myAltRowClass');

JS Fiddle demo.

Or, preferably, just use CSS:

table.myTable tr:nth-child(even) {
    background: #DDDDDC;
}

JS Fiddle demo.

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');

JS Fiddle demo.

Upvotes: 7

Related Questions