Frode Lillerud
Frode Lillerud

Reputation: 7394

Alternate three and three rows in a table with jQuery

I want to set the alternate background color for rows in a table - but the twist is that I don't want every other row to be colored, I want to treat them in blocks of three rows.

So for a table with eight rows I want the first three to be white, then the next three to have a background color, and the last two are back to white again.

How can I do this using jQuery?

Upvotes: 3

Views: 633

Answers (4)

gnarf
gnarf

Reputation: 106352

You could .filter() your result set based on the index of the result:

$("#table tr").filter(function(idx) {
    return (idx % 6) >= 3
}).addClass('alt');

jsfiddle demo

Upvotes: 4

user113716
user113716

Reputation: 322502

If you generated multiple <tbody> elements in your code, you could do it very efficiently like this:

http://jsfiddle.net/jLJMu/

HTML

<table id='mytable'>
    <tbody>
        <tr><td>content</td></tr>
        <tr><td>content</td></tr>
        <tr><td>content</td></tr>
    </tbody>
    <tbody>
        <tr><td>content</td></tr>
        <tr><td>content</td></tr>
        <tr><td>content</td></tr>
    </tbody>
    <tbody>
        <tr><td>content</td></tr>
        <tr><td>content</td></tr>
        <tr><td>content</td></tr>
    </tbody>
    <tbody>
        <tr><td>content</td></tr>
        <tr><td>content</td></tr>
    </tbody>
</table>​​​​​​​​​​​​​​​​​​​​​​

jQuery

$('#mytable tbody:nth-child(2n)').addClass('someClass');​

Upvotes: 1

Ateş G&#246;ral
Ateş G&#246;ral

Reputation: 140060

With possibly a slow selector performance, you could also do this:

$(":nth-child(6n), :nth-child(6n-1), :nth-child(6n-2)", $("#test"))
    .addClass("alt");

And you could even do this entirely with CSS3 (using the nth-child selector), provided that your target browsers all support CSS3 (not yet).

Upvotes: 1

Bob Fincheimer
Bob Fincheimer

Reputation: 18056

Jquery each function should do it:

http://api.jquery.com/jQuery.each/

$('#mytable > tr').each(function(index, ctr) {
    var id = Math.floor(index / 3) % 2;
    if(id == 0) {
       // CHANGE TO COLOR 1
    } else {
       // CHANGE TO COLOR 2
    }
});

The trick is the integer division by 3 [the Math.floor(index/3)], this will give you group of three you are:

rows 0-2 will integer divide to 0 
rows 3-5 will integer divide to 1
rows 6-8 will integer divide to 2

Then you can mod it to get every other...

Upvotes: 3

Related Questions