tags:

views:

750

answers:

6

Hi,

I am using the following code to zebra strip a few tables on one page:

    $(".events-table tr:even").css("background-color", "#fff");
$(".events-table tr:odd").css("background-color", "#efefef");

This is working just fine, but the even/odd intervals are applied to every table on the page. I would like each table to have the same pattern. Meaning, each table should start with the same colour on the first row, then same on the second row, for each table on the page.

Any suggestions?

Thx!

A: 

Try adding IDs to your tables and updating the CSS one table at a time.

clownbaby
+8  A: 

you could probably use a selector for the table and then find the rows to color, ie:

$(".events-table").each(function()
{
    $(this).find("tr:even").css("background-color", "#fff");
    $(this).find("tr:odd").css("background-color", "#efefef");
});
John Boker
Tested and works.
Josh Leitzel
or just use `:nth-child(odd|even)` :)
Russ Cam
+1  A: 

The problem is that the .events-table tr selectors returns a list of trs independent of whether they belong to the same table. The :even and :odd selectors are applied to the complete list.

If you don't have an incredible big amount of tables you could just use ids rather than classes.

$("#events-table1 tr:even").css("background-color", "#fff");
$("#events-table1 tr:odd").css("background-color", "#efefef");
$("#events-table2 tr:even").css("background-color", "#fff");
$("#events-table2 tr:odd").css("background-color", "#efefef");
poezn
+3  A: 

Use :nth-child() (:nth-child(odd) and :nth-child(even)) as opposed to :odd or :even

$("table.events-table tr:nth-child(even)").css("background-color", "#fff");
$("table.events-table tr:nth-child(odd)").css("background-color", "#efefef");

the :odd and :even are actually 0-based, meaning odd rows are 0,2,4, etc. and vice-versa and are used to get odd and even matches in the complete wrapped set.

Take a look at this Working Demo to demonstrate.

nth-child() performs the selection on a parent element basis.

Russ Cam
+1  A: 

The :odd and :even selectors are jQuery-specific "extensions". As mentioned by bluenote, they seem to operate on a list of all elements of the targeted type (in your case, all tr in .events-table.

Alternatives include:

  • Constraining the selector to the table context by passing your table element as the second argument $('tr:odd', mytable).css({})

  • Using the "real" css nth-child selector $('.events-table tr:nth-child(even)').css() though beware of cross-browser compatibility issues.

  • Assigning an 'odd' or 'even' class to the appropriate rows and targeting that explicitly.

Rob Cowie
A: 

Thank-you so much you guys. And, for the explanations as well. Much appreciated :)

Mike