Background
This article was inspired by David F Miller’s Zebra tables article at A List Apart.
I’ve created a JavaScript function to stripe the Waxheads’ results table. I’d been intending to automate the tedious process of adding guide stripes to the Waxheads’ tables for a while but, until seeing David’s article, hadn’t found the impetus.
My solution is a short function that sets the class
of either the odd or even rows of a table. Thus, you can have full control over the guide stripes’ appearance via the page’s stylesheet.
As in David’s example, if the row already has a class
defined then the function won’t replace it with the guide stripe class
.
Implementation
To stripe your table is pretty straightforward. Firstly, identify your table with an id
attribute. For instance:
<table id="myTable" summary="Striped table">
Now, either directly from a <script>
block within the page, or from the onload
attribute in the <body>
tag, call, for example:
tableStripe('myTable' 'myGuideStripeClass', true)
The parameters are, in order, the id of the table, the class name to apply to the row and, finally, a Boolean to determine whether to apply the class to the odd (true) or even (false) rows.
The JavaScript source is fairly succinct. Handily, the DOM provides a rows
attribute in the table
class, which is a list of all the table’s row elements in the order in which they appear. We simply traverse the list and, depending on whether we want to apply our class to odd or even rows and, if the row hasn’t already got a class attribute, we set the row’s className
attribute to our supplied class name.
The rows are indexed from zero, so we set our starting index (zero for an odd start and one for an even start) and then traverse the list in steps of two, checking whether the row already has a class and, if not, applying our own.
I’ve borrowed David’s hasClass()
function, for the IE compatibility reasons he describes in his comment.
For more information about the DOM see Document Object Model (DOM) Level 2 HTML Specification
This article is a work in progress. I’ve noted that both this technique, and David H Miller’s don’t work for IE5.01/Win, I will look to see if there’s a work-around that can be applied in that case – let me know if you find other issues with other browsers.