Alternate Even and Odd Table Row Classes using jQuery

With the CSS3 pseudo element classes being right around the corner, namely :even and :odd, the ability for us web designers to color even and odd rows will soon be as easy as adding this to our CSS documents:

tr:even td {
background-color: #ffffff;
}
tr:odd td {
background-color: #fafafa;
}

But, until browsers support these new pseudo elements, we’ll have to rely on more complex solutions. My favorite, shown below, uses the power of jQuery, which can handle CSS3 selectors and apply CSS2 accessible classes to our elements, namely .even and .odd:

$(document).ready(function() {
$('table.alt tr:odd').addClass('odd');
$('table.alt tr:even').addClass('even');
});

Which will require the following CSS to work:

tr.even td {
background-color: #ffffff;
}
tr.odd td {
background-color: #fafafa;
}

One Response to “Alternate Even and Odd Table Row Classes using jQuery”

  1. This was a great tutorial but can be improved my making the colors a little more contrasted. For a moment there I thought that it wasnt working cause the colors are almost the same. Better to use something like red or blue for the secondary color.

    But, really good tutorial. Really concise and to the point.

    Reply

Comment

  • (will not be published)

XHTML: You can use these tags: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>