Things will go wrong...the Javascript Console is your friend
- United States Senate Table - Plain
- United States Senate Table - Striped with JS
- United States Senate Table - Striped with JS and Console Messages
function stripeTable(tableid) {
let mytable = document.getElementById(tableid);
console.log("mytable is:");
console.log(mytable);
// get tbody (i.e. we dont' want to stripe the thead)
let mytbody = mytable.getElementsByTagName('tbody');
console.log("mytbody is:");
console.log(mytbody);
/* getElementsByTagName gives us a Node List, so we need
to access it as a list (Array), arrayname[i].
Find all the tr within the tbody
*/
let myrows = mytbody[0].getElementsByTagName('tr');
console.log("myrows is:");
console.log(myrows);
console.log("myrows length is: " + myrows.length);
/* Iterate over the node list of "tr" returned, setting
the class appropriately
*/
for(let i=0; i<myrows.length; i++) {
let senatorname = myrows[i].getElementsByTagName('td')[0].firstChild.nodeValue;
console.log(senatorname);
if ((i + 1) % 2 == 0) {
// even rows
console.log("row with index of " + i + " is evenRow");
myrows[i].setAttribute('class','evenRow');
} else {
// odd rows
console.log("row with index of " + i + " is oddRow");
myrows[i].setAttribute('class','oddRow');
}
}
}
console.log()
allows you output messages to a console.