Alternating Row Colors in jQuery

Last week I explained how to color odd and even rows in a table using CSS. today I’m going to show you how you can have the same effect in jQuery. There are two great jQuery selectors which allows you to color alternate rows (i.e. zebra stripes), they are :even and : odd. To see this in action, let’s first define a sample html list:

<ul>
<li>css</li>
<li>html</li>
<li>javascript</li>
<li>jquery</li>
<li>mootools</li>
</ul>

Then add a style to the stylesheet for all css rows, and use an alt class for the even rows:

tr {
    background-color: white;
}
.striped {
    background-color: grey;
}

Now, by using the following jQuery code, you can attach the class to the even-numbered table rows:

$(document).ready(function() {
    $('tr:odd').addClass('stripe');
});

You might be wondering why I added tr:odd for even rows, well, the reason for that is that In javascript the first row counts as 0 (even) and the second row counts as 1 (odd), So if you wanted to color odd rows you would replace code>tr:odd with tr:even.

Leave a Reply