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!
The :odd selector selects each element with an odd index number (like: 1, 3, 5, etc.). The index numbers start at 0. This is mostly used together with another selector to select every odd indexed element in a group (like in the example above). Tip: Use the :even selector to select elements with even index numbers.
:header Selector Selects all elements that are headers, like h1, h2, h3 and so on.
Projects In JavaScript & JQueryjQuery uses CSS selector to select elements using CSS. Let us see an example to return a style property on the first matched element. The css( name ) method returns a style property on the first matched element. name − The name of the property to access.
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");
});
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.
The problem is that the .events-table tr
selectors returns a list of tr
s 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");
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With