Table striping with Javascript
- Use
onload
event attribute of body
element to call striping function. - Will use Document Object Model to access parts of the page
- Basic flow:
- Get the table to stripe (
getElementById
) - Get the table body (
getElementsByTagName
) - Get the rows within the table body (
getElementsByTagName
) - Go through each row, and assign an "evenRow" or "oddRow" class attribute
(for
loop and setAttribute
DOM method)
function stripeTable(tableid) {
let mytable = document.getElementById(tableid);
// get tbody (i.e. we do not want to stripe the thead)
let mytbody = mytable.getElementsByTagName('tbody');
/* 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');
/* Iterate over the node list of "tr" returned, setting
the class appropriately
*/
for(let i=0; i<myrows.length; i++) {
if ((i + 1) % 2 == 0) {
// even row -- the "%" operator is the "modulus" or remainder
myrows[i].setAttribute('class','evenRow');
} else {
// odd row
myrows[i].setAttribute('class','oddRow');
}
}
}