RyJ
RyJ

Reputation: 4025

Coloring odd rows for multiple tables

If I have more than one table on a page, and I try coloring the odd rows, jQuery seems to merge the entire group of TRs (from all tables) together when it does its determining of which rows are odd.

See example: http://jsfiddle.net/ryjennings/KNmuQ/5/

Is there a way to stop jQuery from doing this and treat each table separately?

Upvotes: 1

Views: 1906

Answers (5)

Web User
Web User

Reputation: 7736

This one processes rows relative to parent table, as opposed to the code you are using...

$(document).ready(function() {
    $("tr:nth-child(even)").each(function() {
        $(this).addClass('odd');
    });
});

Upvotes: 0

Ansel Santosa
Ansel Santosa

Reputation: 8444

You should not be using Javascript for anything that you can do with CSS. CSS is orders of magnitude faster. What you need is the :nth-child psudo-class:

tr:nth-child(odd) { background:#f5f6f8; }

See Fiddle.

Upvotes: 1

Ruslanas Balčiūnas
Ruslanas Balčiūnas

Reputation: 7418

$(document).ready(function() {
    $("table").each(function(){
        $(this).find('TR:even').addClass("odd");
    });
});

Upvotes: 0

Joseph Marikle
Joseph Marikle

Reputation: 78520

This is one way you could do it:

$("table").each(function(){
    $("tr:even", this).addClass("odd");
});

Upvotes: 0

David Brainer
David Brainer

Reputation: 6331

You could do this instead:

$(document).ready(function() {
    $("table").find("TR:even").addClass("odd");
});

Basically, your original selector was grabbing a group of all of the tr elements contained within tableelements on the page, which was all of them, and then taking every other one of that huge set. The new series of selectors first creates a group of all the tables and then a sub group of the rows within each table and then takes every other one of the rows in each sub group.

Upvotes: 6

Related Questions