DZone Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world

Snippets has posted 5883 posts at DZone. View Full User Profile

Zebra A Table

05.30.2005
| 8848 views |
  • submit to reddit
        
<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>
    

Comments

Snippets Manager replied on Mon, 2012/05/07 - 2:12pm

Very useful. thanks!