Easy Zebra Striping with Prototype
While reviewing some of the JQuery tutorials, I was impressed with the ease of setting up a table with alternating row colors.
This got me thinking that it should be a relatively easy thing to achieve using the Prototype library as well. In this edition, I will give quick example of doing just that.
We’ll start by using the element selector utility method ($$). This will return a list of the odd numbered rows in our table. We then add the oddRow classname to each of these matched table rows.
function stripe(e) { var evens = $$('table.stripe tr:nth-child(odd)'); if(evens) { evens.each(function(tr) { tr.addClassName('oddRow'); }); } } Event.observe(window, 'load', stripe);
The next step is to assign the stripe class to our table. Any table with this class will pick up the new behavior.
Last step, we need to specify the CSS to change the background color. I also threw in a directive to collapse the borders.
table.stripe tbody tr.oddRow { background-color: #eee; } table.stripe { border-collapse: collapse; }
Here it is in action. Though it’s a bit crude it illustrates that the rows are highlighted as intended.
| Lorem | Ipsum | Dolor | Sit | Amet |
|---|---|---|---|---|
| Lorem | Ipsum | Dolor | Sit | Amet |
| Lorem | Ipsum | Dolor | Sit | Amet |
|---|---|---|---|---|
| Lorem | Ipsum | Dolor | Sit | Amet |
| Lorem | Ipsum | Dolor | Sit | Amet |
| Lorem | Ipsum | Dolor | Sit | Amet |
| Lorem | Ipsum | Dolor | Sit | Amet |
| Lorem | Ipsum | Dolor | Sit | Amet |
| Lorem | Ipsum | Dolor | Sit | Amet |
| Lorem | Ipsum | Dolor | Sit | Amet |
| Lorem | Ipsum | Dolor | Sit | Amet |
| Lorem | Ipsum | Dolor | Sit | Amet |
| Lorem | Ipsum | Dolor | Sit | Amet |
As always improvements, tweaks & suggestions are welcome.

21:44 on July 15
I like your method (especially the tr:nth-child(odd) part of $$). Only thing I would suggest is running stripe on DOMReady. Does prototype have a way to attach an event to DOMReady?
Nice example!
22:01 on July 15
Thanks Eric,
While it may run a bit after the DOM is ready (especially on larger pages), the Event.observe() does just that. It will invoke the stripe function when the window’s onload event fires.
It doesn’t look like prototype has an equivalent DOMLoaded event. The link below has a very convoluted example of achieving the same thing. But, it’s a bit of a hack with its browser specific Javascript.
http://tanny.ica.com/ica/tko/tkoblog.nsf/dx/domcontentloaded-for-browsers-part-ii
07:43 on July 23
@watsoncj, It is a bit of a hack and I have a smaller version for prototype and other frameworks that don’t support domready. Unfortunately the only way to support as many browser as I can, I have to use “browser specific Javascript”.
DOMContentLoaded for Browsers, Part V
13:05 on September 5
The equivalent in Prototype is:
document.observe(’dom:loaded’, function () {});