Alternating Row Colors in jQuery

Alternating row colors in jQuery can be easily done using :even and :odd selectors. Let's apply these selector to a list and see the effect.

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:


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() {

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.

Have your say