How To Alter Background Colours Of HTML Table Rows With jQuery

If you have long lists of data displayed as tables, it may be a bit confusing to read a line across its columns. But there is an easy way to make your tables more readable. Just alter the background-colour of your list line-by-line.

In this post I’ll show you how to do this by using jQuery. First of all we need a table with some sample data for demonstration:

<!DOCTYPE html>
<html>
<head>
    <title>Alter Row Colour With jQuery</title>
</head>
<body>
    <table id="tbl">
        <thead>
            <tr>
                <td>Amy</td>
                <td>M.</td>
            </tr>
            <tr>
                <td>Fred</td>
                <td>G.</td>
            </tr>
            <tr>
                <td>Lisa</td>
                <td>F.</td>
            </tr>
            <tr>
                <td>Joe</td>
                <td>K.</td>
            </tr>
            <tr>
                <td>Mia</td>
                <td>A.</td>
            </tr>
            <tr>
                <td>Cedric</td>
                <td>P.</td>
            </tr>
            <tr>
                <td>Kay</td>
                <td>D.</td>
            </tr>
            <tr>
                <td>Pierre</td>
                <td>C.</td>
            </tr>
        </tbody>
    </table>
</body>
</html>

The table has the id tbl, so you can access it by this identifier later.

In the next step you’ll have to add jQuery to your HTML File. I do this by usign the Google CDN. So in the head-Section of your HTML File you’ll have to load jQuery:

<head>
<!-- This adds jQuery -->
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.3/jquery.min.js"></script>
</head>

Now it’s time for some styling. Just add the following CSS into your HTML File, either into <head> section or into <body> section.

<style>
    .odd {
        background-color:#b0b0b0;
    }
    .even {
        background-color:#e0e0e0;
    }
</style>

One last step to do: add the following code, e.g. before the closing <body> tag.

<script>
    $(document).ready(function() {
        $('#tbl tr:odd').addClass("odd");
        $('#tbl tr:even').addClass("even");
    });
</script>

Finished! Now your table is displayed with different background-colours for odd and even lines.

(Visited 181 times, 1 visits today)

1 thought on “How To Alter Background Colours Of HTML Table Rows With jQuery”

  1. Why you don’t just use nth-child? :/

    #tbl tr:nth-child(odd) td {
    background-color:#b0b0b0;
    }
    #tbl tr:nth-child(even) td {
    background-color:#e0e0e0;
    }

    Reply

Leave a Comment