Zebra tables revisited
Posted by Jorge Bernal February 13, 2006
Some time ago, I read an article about Zebra tables with javascript. This methods saves a lot of unnecessary markup, but has some flaws:
- You can only invoke it for a specific table
- It doesn’t work if the
tdortrhas aclassdefined.
So I have rewritten this library to match all the tables with the same class (eg. listing).
function stripe(cls) {
// the flag we'll use to keep track of
// whether the current row is odd or even
var even = false;
// obtain a reference to the desired table
// if no such table exists, abort
var tables = document.getElementsByTagName("table");
for (var t = 0; t < tables.length; t++) {
if (tables[t].className == cls) {
// by definition, tables can have more than one tbody
// element, so we'll have to get the list of child
// tbody's
var tbodies = tables[t].getElementsByTagName("tbody");
// and iterate through them...
for (var h = 0; h < tbodies.length; h++) {
// find all the tr elements...
var trs = tbodies[h].getElementsByTagName("tr");
// ... and iterate through them
for (var i = 0; i < trs.length; i++) {
trs[i].className =
even ? 'tr_even' : 'tr_odd';
// flip from odd to even, or vice-versa
even = ! even;
}
}
}
}
}
Then you can define your row styles like:
tr.tr_even { background-color: #ffffff; }
tr.tr_odd { background-color: #ecddac; }
