Automatic Table Styling with Javascript.
January 10, 2008
A while back a wrote a JavaScript script that automatically styled an HTML table. In a nutshell, the script automatically changes the background color of every 2nd row in an HTML table.
Anyway, someone recently sent me an updated version of the script. You will probably want to read the original article before looking at these changes.
From the email:
I did some simplification on the code for zebrastripes. I don’t bother with the last array bit because TR elements have the bgColor attribute.
trs[i].bgColor = ( i & 1 ) ? stripe_colour_even : stripe_colour_odd;
Greetings,
tarjei
The complete function:
function stripe_table(id_name) {
var my_table = document.getElementById(id_name);
/* For debugging */
if ( !my_table ) {
alert(“The ID ” + id_name + ” is not found.”);
return;
}/* Table may have more than one tbody element */
var tbodies = my_table.getElementsByTagName(“tbody”);for (var cnt = 0; cnt < tbodies.length; cnt++) { var trs = tbodies[ cnt ].getElementsByTagName("tr"); /* Walk table row for row */ for (var i = 0; i < trs.length; i++) { if (! hasClass(trs[i]) && ! trs[i].style.backgroundColor) { trs[i].bgColor = ( i & 1 ) ? stripe_colour_even : stripe_colour_odd; } } } } }
CIAO.
Stefan Mischook