Alter Table Row Background Colors(Zebra rows for Tables) Using JavaScript

This first example uses a style element through which we have defined two classes for background colors:

<style>
.odd{background-color: white;}
.even{background-color: gray;}
</style>

The style is flexible: it could just as well define something else, such as that every second row should display in italics. The complete function looks like this:

function alternate(id){
if(document.getElementsByTagName){
var table = document.getElementById(id);
var rows = table.getElementsByTagName("tr");
for(i = 0; i < rows.length; i++){
//manipulate rows
if(i % 2 == 0){
rows[i].className = "even";
}else{
rows[i].className = "odd";
}
}
}
}