I have the following script working to add odd and even classes to alternating table rows which works fine.
function alternate(){
if(document.getElementsByTagName){
var table = document.getElementsByTagName("table");
var rows = document.getElementsByTagName("tr");
for(i = 0; i < rows.length; i++){
//manipulate rows
if(i % 2 == 0){
rows[i].className = "even";
}else{
rows[i].className = "odd";
}
}
}
}
However a problem arises when there is more than one table on a page. I need the counter to reset for each table on the page so the first row of each table always has the same class (i.e. odd). Currently the second table on the page will just carry on counting rows odd-even so it will start on a different class if the first table has an odd number of rows.
Can anyone help me change this code to achieve this?
Here you go:
Live demo: http://jsfiddle.net/simevidas/w6rvd/
Alternative solution:
(Substituting the
foriteration statements withforEachinvocations makes the code more terse. Doesn’t work in IE8 though:/.)Live demo: http://jsfiddle.net/simevidas/w6rvd/1/