Alternate Row Styles in Tables

Even though we use table-less CSS layouts, there are still a lot of times where we still need to use tables for tabular data. Using classes to affect the row colors can be a pain sometimes. Ever catch yourself doing this?

<table>
    <tbody>
        <tr class="odd">
            <td>Row 1</td>
        </tr>
        <tr>
            <td>Row 2</td>
        </tr>
        <tr class="odd">
            <td>Row 3</td>
        </tr>
    </tbody>
</table>

Adding a class to each row is error prone and takes way too much time. To get around this, a good idea is to use a little JavaScript.

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

This simple JavaScript takes a table of a certain ID and finds the number of rows. Looping through the rows, it divides the row count by 2 to see if there is a  remainder. No remainder, it’s even, else  it’s odd. Finally, it automatically inserts the appropriate class. Works great on large tables (<1000 rows). Simply use CSS to style the even and odd classes.

To use, simply attach an event handler:

<body onload="alternate('idOfMyTable')">
TobbyAlternate Row Styles in Tables

Leave a Reply

Your email address will not be published. Required fields are marked *