User login

Alternate Row Colors in HTML Table with JavaScript

If you have an HTML table with a lot of rows, it may be useful to have a different background color for alternate rows.


OneOne
TwoTwo
ThreeThree
FourFour


Most of the methods used to create this effect involve different style classes for alternate rows, like the following for example:

<tr class='odd'>... </tr>
<tr class='even'>... </tr>
<tr class='odd'>... </tr>

and then assigning different backrounds for these styles. The downside of this method is that you have to create alternate style classes for each row.

There is a simpler way to apply alternate colors without each row having a distinct style class. All you need is for a table to have an id, for example "myTable".
Use the following JavaScript code to apply a different background color to alternate rows in that table.


function applyColors(){
var bgColor = '#ECF6FC';
var tbl = document.getElementsByTagName('table')[0];
for (j=0;j<tbl.rows.length;j++)
if(j%2==0) tbl.rows[j].style.background= bgColor;
}
window.onload=applyColors;

Code Explanation

First we obtain a reference to the html table:
var tbl = document.getElementsByTagName('table')[0];

This code grabs the first table on a page.

Then, we loop through each row. If it is an even row (row numbering starts at 0), we assign a different background style to the row.