Reputation: 4025
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
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
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; }
Upvotes: 1
Reputation: 7418
$(document).ready(function() {
$("table").each(function(){
$(this).find('TR:even').addClass("odd");
});
});
Upvotes: 0
Reputation: 78520
This is one way you could do it:
$("table").each(function(){
$("tr:even", this).addClass("odd");
});
Upvotes: 0
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 table
elements 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