I am currently on a project that has a page with many HTML tables (don’t judge me :) ).  The users wanted the rows to have alternating colors for each row as so many sites do these days.  I was trying to think of the easiest way to do this, and since my jQuery is a little iffy (I have not used it much yet – again, don’t judge me :) ), I decided to see if I could whip something up relatively quickly.  My first attempt was the following:

<script type="text/javascript">
    $(document).ready(function () {
        $('table.colorized').each(function (tblIndex) {
            $(this).find('tr').each(function (rowIndex) {
                if (rowIndex % 2 == 1) {
                    $(this).css('background-color', '#EAEAEA');
                }
            });
        });
    });
</script>

 

What’s happening:

1) I added a CSS class of “colorized” to each table I cared about.

2) The $('table.colorized') statement selects all tables with the colorized class.

3) .each() creates a for loop around the results, so the code is iterating through the tables.

4) For each table, we look for any <tr> sub-tags.

5) We iterate through the <tr> tags, and on every other one, we add a background color.

This worked great except for one instance where the cells of one of the tables contained yet another table (ok, you can judge me now :) ).  I began searching for a solution.

.children() to the rescue.  Using the .children() function in jQuery, I can get only the rows that are direct descendants of the table I care about.  So I tried this:

<script type="text/javascript">
    $(document).ready(function () {
        $('table.colorized').each(function (tblIndex) {
            $(this).children('tr').each(function (rowIndex) {
                if (rowIndex % 2 == 1) {
                    $(this).css('background-color', '#EAEAEA');
                }
            });
        });
    });
</script>

 

Well, that didn't work at all.  Now none of the tables had the alternating colors.  What did I screw up?  Well, I forgot about the fact that modern browsers throw in a <tbody> tag into the HTML, so my .children() call was only finding the <tbody> tag.  Thus, my final solution ended up being the following:

<script type="text/javascript">
    $(document).ready(function () {
        $('table.colorized').each(function (tblIndex) {
            $(this).children().children('tr').each(function (rowIndex) {
                if (rowIndex % 2 == 1) {
                    $(this).css('background-color', '#EAEAEA');
                }
            });
        });
    });
</script>

This way, I select the children of the <tbody> and <poof> everything works as expected.  jQuery is awesome!