In the code below, I am applying a different background color to all even rows by dynamically assigning the class \"even\" to them using javascript. I am calling the alternamte(
It's getElementsByTagName(), plural. It returns a HTMLCollection
var table = document.getElementsByTagName("table")[0];
(if you're confident that there's a <table>
on the page.)
If you want to do things to all the <table>
elements, you'd have to do something like this:
var tables = document.getElementsByTagName("table");
for (var ti = 0; ti < tables.length; ++ti) {
var rows = tables[ti].getElementsByTagName("tr");
for(var i = 0; i < rows.length; i++){
//change style of even rows
//(odd integer values, since we're counting from zero)
if(i % 2 == 0){
rows[i].className = "even";
}
}
}
getElementsByTagName() returns an array matching the selector. Hence try
var table = getElementsByTagName('table')[indexnumber];
Use getElementsByTagName
instead of getElementByTagName
(getElementsByTagName return multiple node elements )
var table = document.getElementsByTagName("table")[0], trs, rl;
vat tl= table.length;
while(tl--){
trs = tables[tl].getElementsByTagName("tr");
rl = trs.length;
while(rl--){
if(rl % 2 == 0){
trs[rl].className = "even";
}
}
}