Search code examples
javascriptjqueryjquery-1.3

More efficent method of styling alternating blocks of table rows with jQuery?


Doing odd/even styling with jQuery is pretty easy:

$(function() {
  $(".oddeven tbody tr:odd").addClass("odd");
  $(".oddeven tbody tr:even").addClass("even");
});

Now I came across an interesitng problem today. What if you want to style alternating groups of elements? For example, alternating blocks of 3. Longhand this can be done this way:

$(function() {
  $(".oddeven3 tbody tr:nth-child(3n+1)").addClass("odd");
  $(".oddeven3 tbody tr:nth-child(3n+2)").addClass("odd");
  $(".oddeven3 tbody tr:nth-child(3n+3)").addClass("odd");
  $(".oddeven3 tbody tr:nth-child(3n+4)").addClass("even");
  $(".oddeven3 tbody tr:nth-child(3n+5)").addClass("even");
  $(".oddeven3 tbody tr:nth-child(3n+6)").addClass("even");
});

Seems a bit longwinded though. Now it can be somewhat simplified and made generic like this:

function oddEvenGroupStyle(groupSize) {
  for (var i=1; i<=groupSize; i++) {
    $(".oddeven" + groupSize + " tbody tr:nth-child(" + groupSize + "n+" + i + ")").addClass("odd");
    $(".oddeven" + groupSize + " tbody tr:nth-child(" + groupSize + "n+" + (groupSize+i) " + ")").addClass("even");
  }
}

and:

$(function() {
  oddEvenGroupStyle(3);
});

Seems like a bit of a hack to me though. Is there some more jQuery-ish way of selecting the right rows?


Solution

  • function oddEvenGroupStyle(groupSize) {
        var even = false;
        $('tr').each( 
            function(i){ 
                if(!(i % groupSize)) even = !even;
                $(this).attr('class', (even ? 'groupEven':'groupOdd') ); 
        })
    }