Rate this script:  I Love it  /   I Hate it

zebra a table


Code


<html>
  <head>
    <script>
      function init () {
        var tables = document.getElementsByTagName("table");
        for (var i = 0; i < tables.length; i++) {
          if (tables[i].className.match(/zebra/)) {
            zebra(tables[i]);
          }
        }
      }

      function zebra (table) {
        var current = "oddRow";
        var trs = table.getElementsByTagName("tr");
        for (var i = 0; i < trs.length; i++) {
          trs[i].className += " " + current;
          current = current == "evenRow" ? "oddRow" : "evenRow";
        }
      }
    </script>
    <style>
        tr.oddRow { background-color: green; }
        tr.evenRow { background-color: red; }
    </style>
  </head>
  <body onload="init()">
    <table class="zebra">
      <tr> <td>foo</td> <td>foo</td> <td>foo</td> </tr>
      <tr> <td>bar</td> <td>bar</td> <td>bar</td> </tr>
      <tr> <td>foo</td> <td>foo</td> <td>foo</td> </tr>
      <tr> <td>bar</td> <td>bar</td> <td>bar</td> </tr>
      <tr> <td>foo</td> <td>foo</td> <td>foo</td> </tr>
    </table>
  </body>
</html>
 

 

 
zebra a table scripts | zebra a table snippet | zebra a table example | zebra a table tutorial | zebra a table code