Adding zebra stripes to a table adds a nice touch of usability for your audience and a bit of style to something, more often than not, visually boring. Doing this manually by adding classes of odd and even to alternate rows is a tedious task, especially if the data is constantly changing. As if this wasn't an issue for one familiar with markup, try to ask a client to do this when you hand a site off to them.
Enter JavaScript (well… jQuery)
Why do these things manually when you have a perfect tool with which to manipulate the DOM and do this for you? With JavaScript you can add the classes necessary for adding alternate classes to your table without touching the markup yourself. If you happen to be using jQuery then the task is as simple as adding a few short lines of code:
$(document).ready(function () {
$("table tbody tr:odd").addClass("odd");
$("table tbody tr:even").addClass("even");
});
Voila! You know have a class on every other table row with which to style to your heart's content. This is the code I usually implemented for the sites I worked on and for the most part this worked beautifully. With a recent project, however, this method proved inadequate.
The Problem
The problem arose when the design called for two tables to be displayed side by side. They were both just about the same length in the comp, and when I applied the usual method to achieve the striped effect, it worked without a hitch. When the code was passed along to the client, it all fell apart when they added another row to the table. Now when the striping was applied we got this:
The Solution
Two solutions actually. Google once again proved that you can find the answer to any question in a matter of seconds. By typing in "jQuery table striping issues" I came across an article by Trevor Davis regarding the issue was having with my tables. Trevor offered up an alternative to the usual method of striping by using nth-child:
$(document).ready(function () {
$("table tbody tr:nth-child(odd)").addClass("odd");
$("table tbody tr:nth-child(even)").addClass("even");
});
It worked like a charm and I could have stopped there, but reading the comments to the article I found that it wasn't really an issue with the method I was using rather that I wasn't resetting the striping for each new table on the page. This next bit of code was offered by Andy Couch and also achieves the desired results:
$(document).ready(function () {
$("table").each(function () {
$("table tbody tr:odd").addClass("odd");
$("table tbody tr:even").addClass("even");
});
});
Both solutions by Trevor and Andy work well, and as was noted in the comments of the article there are probably a hundred different ways to fix the problem.