I have a page with several tables on it with the same class name. I want to alternate the colors of the rows of every table on this page. I’m using the code below with . This code isn’t working correctly, because only 1 table is alternating colors at a time (the first table). what am I doing wrong? All the tables on my page has “mytable” class.
function altrows(classname,firstcolor,secondcolor)
{
var tableElements = document.getElementsByClassName(classname) ;
for(var j= 0; j < tableElements.length; j++)
{
var table = tableElements[j] ;
var rows = table.getElementsByTagName("tr") ;
for(var i = 0; i < rows.length; i=i+2)
{
rows[i].bgColor = firstcolor ;
rows[i+1].bgColor = secondcolor ;
}
}
}
If one of your tables has an odd number of rows, your function will break on the line
and not process any of the following tables. You should either check whether there is a row before setting the secondcolor:
or loop over every row rather than looping over sets of two rows: