Archive for November, 2006

Zebra Tables Revisited

On a project I’m working on, I needed to style some data tables in a few pages with alternating background colors for each row. The tables would be living in static html documents rather than being generated server side, so there wasn’t going to be any cycling styles in a loop.

I remembered the A List Apart article on the subject and applied it to my pages. I quickly realized the limitations of their implementation. Calling the function with a DOM ID for every table I wanted to style just wasn’t going to cut it. I didn’t like limiting the styling to the background color either.

So here’s my alternative…


function ASZebraStripes(cssClass) {
  var evenClass = arguments[1] ? arguments[1] : 'even';
  var oddClass  = arguments[2] ? arguments[2] : 'odd';
  var zebras = new Array();
  var tables = document.getElementsByTagName('table');
  for (i = 0, j = 0; i < tables.length; i++) {
    if (new RegExp("\\b"+cssClass+"\\b").test(tables[i].className)) {
      zebras[j] = tables[i]; j++;
    }
  }
  for (i = 0; i < zebras.length; i++) {
    var tbodies = zebras[i].getElementsByTagName('tbody');
    var parity = false;
    for (j = 0; j < tbodies.length; j++) {
      var trs = tbodies[j].getElementsByTagName('tr');
      for (k = 0; k < trs.length; k++) {
        newClass = parity ? evenClass : oddClass;
        trs[k].className += trs[k].className ? ' '+newClass : newClass;
        parity = !parity;
      }
    }
  }
}

 

The only required argument is the css class of the tables you want to stripe. You can optionally pass 2 more parameters representing even and odd class names for your tr tags. The function essentially just gets every table in the page, picks out the ones that match our css class and loops through their rows appending even or odd classes as it goes.

Find the latest version and more JavaScript in my respository