Alternative three and three rows in a table with jQuery

I want to set an alternative background color for the rows in the table, but the rotation is that I do not want every other row to be colored, I want to process them in blocks of three rows.

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

How to do it using jQuery?

+3
source share
4 answers

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

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

jsfiddle demo

+4
source

Jquery every function should do this:

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
    }
});

- 3 [Math.floor(index/3)], :

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

, ...

+3

, :

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

And you could do it completely with CSS3 (using a selector nth-child), provided your target browsers support CSS3 (not yet).

+1
source

If you have created several elements in your code <tbody>, you can do this very efficiently:

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');​
+1
source

Source: https://habr.com/ru/post/1750554/


All Articles