Wednesday, January 17, 2007

Alternating HTML table Row Styles with javascript and CSS

In a website that we built for a clients we had to use alternating row styles for the tables. When I generate tables dynamically using server side code this is pretty easy. I can just specify a different class for each . If the tables are static this becomes a mess. For one of our web designers had to hand code the classes for each of the rows and each time we had to add or remove a row he had to edit all consecuitive rows.
For another website we were working on I had used a different approach. Using JavaScript and CSS I set a class for the table (altRows). When the page load I look for all the table elements and traverse the rows, setting the different classes for alternating rows. If a row already has a class defined the script will not change it which makes it perfect for header rows etc. I tested the solution in IE, Firefox and Opera and it works :)
The code is listed below:

function alternateRowStyles()
var i, j;
var table;
for( i =0; i < document.getElementsByTagName("table").length; i++) { if( document.getElementsByTagName("table")[i].className == "altRows") { table = document.getElementsByTagName("table")[i]; for ( j = 0; j < table.rows.length; j++) { if (table.rows[j].className == "") { if (j%2 == 0 ) { table.rows[j].className = "oddClass"; } else { table.rows[j].className ="evenClass"; } } } } } }
You can see it in action at

If you want to download the code including a function that will wire the function to the onLoad event of the page you can do so at:

1 comment:

Miki Mullor said...

I was on Google looking for something, came across this blog, and Walla: I know this guy!