Search code examples
javascriptjquerydomtablesorter

Reset an elements 'odd' or 'even' status?


I have a table with 'zebra stripes' which adds a class to every second, or 'even', <tr>, eg:

 $("#summarytable tr:even").addClass("even");

I am also using the Table Sorter plugin which allows the sorting columns alphabetically and numerically if a <th> is clicked.

The problem is that 'even' <tr>s remain 'even' even after they've been sorted by the plugin and their order shuffled. So, even if I remove and then add the '.even' class again, eg:

$("#summarytable th").click(function() {
    $("#summarytable tr").removeClass("even");
    $("#summarytable tr:even").addClass("even");
});

It still appears out of order.

Is there someway to 'reset' the order of elements in the DOM and thus reset an elements 'odd' or 'even' status?

Dev example here: http://ryanturner.com.au/tipping/index.php?id=4


Solution

  • If the striping is only for styling, you can sidestep this whole problem just using CSS.

    Example:

    tr:nth-child(2n) {
        background: gray;
    }
    tr:nth-child(2n+1) {
        background: lightgray;
    }
    

    If you really need some function to run after sorting takes place, a quick glance at the documentation suggests that you might do it like this:

    $("table").bind("sortEnd", function() { 
        // ...
    });