Dynamically change CSS class of a row in a table

Cheri picture Cheri · May 26, 2011 · Viewed 9.8k times · Source

I have a simple table:

<table> <tr class="none"><td>value</td><td>value</td></tr></table>

I then need to check all the values of the cells in every row. If all of the values are not the same for a given row, then I need to change the class of the row from "none" to "active". Is there a way to do this using jQuery?

Answer

pixelbobby picture pixelbobby · May 26, 2011

Something like the below would work. Also, I would recommend using <thead> and <tbody> in your <table> for proper markup. Update: corrected function below to check values of other rows; as soon as a different value is encountered, the <tr> is updated with a class accordingly.

Fiddle Demo: http://jsfiddle.net/kaCAF/4/

<script type="text/javascript">
$(document).ready(function() {
    $('#myTable tbody tr').each(function() {

        //compare each cell to adjacent cells
        $(this).find('td').each(function() {
            var $val = $(this).text();

            //checks for different values.  as soon as a difference
            //is encountered we move to next row
            $(this).parent().find('td').each(function() {
                if ($(this).text() != $val) {
                    $(this).parent().addClass('different');
                    return false;
                }
            });
        });
    });

});
</script>

<table id="myTable" border="1">
    <thead>
        <tr><th>Col1</th><th>Col2</th><th>Col3</th></tr>
    </thead>
    <tbody>
        <tr><td>Val 1</td><td>Val 1</td><td>Val 2</td></tr>
        <tr><td>Val 1</td><td>Val 2</td><td>Val 2</td></tr>
        <tr><td>Val 3</td><td>Val 3</td><td>Val 3</td></tr>
        <tr><td>Val 123</td><td>Val 123</td><td>Val 123</td></tr>
    </tbody>
</table>