How to use alternate row color in a html table

Js

Posted on 13 May 15 by Vickey
  1274



For showing each row different we can use alternate row color in a table. For give different color we need to add a differnt style or different backgrownd color here is a way to give different background color to alternate rows In this example i have a table with id "diffcolor".

<table style="width:100%" id="diffcolor">
  <tr>
    <td>Jack</td>
    <td>Smith</td> 
    <td>50</td>
  </tr>
  <tr>
    <td>Paul</td>
    <td>Jackson</td> 
    <td>94</td>
  </tr>
    <tr>
    <td>Alen</td>
    <td>Smith</td> 
    <td>50</td>
  </tr>
      <tr>
    <td>Jill</td>
    <td>Smith</td> 
    <td>50</td>
  </tr>
        <tr>
    <td>Bob</td>
    <td>Joy</td> 
    <td>50</td>
  </tr>
</table> 

here is js function for add different background color to the alternate rows

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

and now we need to call this function and pass table id

tableRowColor('diffcolor');

this function will add different class on table's rows now we need to give style

   .even{
    background: #f2f2f2;
   }
   .odd{
    background: #fff;
   }

If this post help you reduce time to develop, you can help me to maintain this website :)
www.000webhost.com