Tables with alternating backgrounds
using JavaScript and DOM

DEPRECATED The JavaScript approach to this problem is no longer recommended. It is much better to use CSS3 unless you must support very old web browsers. See Tables with alternating backgrounds using CSS.

Sometimes it’s nice to have a table or list whose background colors alternate. It’s easy to generate such formatting automatically. But if you make the list by hand, it’s not so easy: you have to explicitly specify the color of each row in the list. And then you want to add a single row somewhere in the middle? Oy!

Either way, you at have to put explicit style info (or alternating class attributes) in each row, making the HTML rather messy, effectively mixing content with presentation.

No more. Just point the JavaScript function alternateTableRowBGColor(table_ID), at the table. It does the alternating colors for you on the fly in the user’s browser!

The Western Civ Complete CSS Guide used to say CSS2 has a selector for alternating rows (and columns) but as of this time, no web browser supports it. However, I see no mention of such a selector in the standard reference at W3 CSS2 page and the Western Civ passage I mentioned is gone.

This will work only with DOM-compliant web browsers, Firefox, Opera 7–10, MSIE 6–7, Konqueror 3.1+, and Chrome. However, it shouldn’t hurt non-DOM compliant browsers if used correctly.

One other caveat: I broke this accidentally by including a style sheet that set the background-color of td elements. It seems that in that case, styles set by the script aren’t evaluated. I don’t really understand how cascading is supposed to work in such cases, but by setting the background-color of td elements to inherit instead, it was fixed.

To use it, copy the script from the source of this HTML page into the head section of your HTML page, give each table in the document a unique id attribute, and in the onload attribute of the body element, call alternateTableRowBGColor(table_ID) for each table to which you assigned an id.