The easiest way to generate alternating colored rows for multiple tables using JavaScript and DOM.

Easily generate an alternating colored rows table by simply embedding the class "striped" into the table.

Following is a table with class "striped".

Name Position Location
John Doe Web Developer Shoreline, WA
Bill Matthew Network Administrator Seattle, WA
Dan Graphic Designer Seattle, WA
Marissa CEO Seattle, WA

Following is a table without class "striped".

Name Position Location
John Doe Web Developer Shoreline, WA
Bill Matthew Network Administrator Seattle, WA
Dan Graphic Designer Seattle, WA
Marissa CEO Seattle, WA

How to use?

1. Simply add the following code into your JavaScript:

<!-- JS that converts all tables with class "striped" into a striped table! ~duh -->
<!-- created by Heru Setiawan (from Chazown Web - www.chazownweb.com) -->
<!-- March 7, 2008 -->
<!-- You are FREE TO USE this code but this information should remain. -->
<script language="javascript">
// create alternating colored rows for all tables that have class "striped"
function stripeTable()
{
  // get all tables in the document
  var tables = document.getElementsByTagName("table");
  // for each table
  for(var i = 0; i < tables.length; i++)
  {
    var table = tables[i];
    // check if the table has a class striped
    if(table.className == "striped")
    {
      // if it has, then go for each row
      var row_count = 0;
      var rows = table.getElementsByTagName("tr");
      for(var j = 0; j < rows.length; j++)
      {
        var row = rows[j];
        var class_tmp = "";
        // if the row does not have a class header
        if(row.className != "header")
        {
          // generate the row color
          if(row_count % 2 == 0) class_tmp = "even"; else class_tmp = "odd";
          row.setAttribute("class",class_tmp);
          row.className = class_tmp;
          row_count++;
        }
      }
     }
  }
}
</script>

2. Add stripeTable() to your body onload:

<body onload="stripeTable();">

3. Simply add class stripe into the table that you want to get it striped.

<table width="100%" border="0" cellspacing="1" cellpadding="3" class="striped">

Voila~! You get the effortless way of creating the alternating colored row tables. The good news is that you can use onto as many tables as possible. Thanks to DOM and JavaScripting! :)

The bad news is that it will only work if the JS is enabled and it will now show up in your printer.

Return to our blog