Home > Net >  Dynamically add incrementing class between multiple nth-children(n )
Dynamically add incrementing class between multiple nth-children(n )

Time:11-22

I am looking to add an incrementing class between every 4 children.

So, "Item 1 to Item 4" should have the class ".summary-item-1" and then "Item 5 to Item 7" should have the class ".summary-item-2" and so on without stopping.

 $(document).ready((function() {
    $(".carousel-slides-view-4").each((function() {
            $(this).find(".summary-item:nth-child(4n 1)").each((function(n) {
                $(this).addClass("summary-item-"   (n   1))
        }))
    }))
  }));
.summary-item-1 {
color: red;
}

.summary-item-2 {
color: blue;
}

.summary-item-3 {
color: green;
}

.summary-item-4 {
color: yellow;
}

.summary-item-5 {
color: orange;
}

.summary-item-6 {
color: violet;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<div >

<div >Item 1</div>
<div >Item 2</div>
<div >Item 3</div>
<div >Item 4</div>
<div >Item 5</div>
<div >Item 6</div>
<div >Item 7</div>
<div >Item 8</div>
<div >Item 9</div>
<div >Item 10</div>
<div >Item 11</div>
<div >Item 12</div>
<div >Item 13</div>
<div >Item 14</div>
<div >Item 15</div>
<div >Item 16</div>
<div >Item 17</div>

</div>

CodePudding user response:

Please try to use this code

document.querySelectorAll('.summary-item').forEach((element,index) => {
  const itemIndex = parseInt(index / 4)   1;
  element.classList.add(`summary-item-${itemIndex}`);
});
.summary-item-1 {
color: red;
}

.summary-item-2 {
color: blue;
}

.summary-item-3 {
color: green;
}

.summary-item-4 {
color: yellow;
}

.summary-item-5 {
color: orange;
}

.summary-item-6 {
color: violet;
}
<div >

<div >Item 1</div>
<div >Item 2</div>
<div >Item 3</div>
<div >Item 4</div>
<div >Item 5</div>
<div >Item 6</div>
<div >Item 7</div>
<div >Item 8</div>
<div >Item 9</div>
<div >Item 10</div>
<div >Item 11</div>
<div >Item 12</div>
<div >Item 13</div>
<div >Item 14</div>
<div >Item 15</div>
<div >Item 16</div>
<div >Item 17</div>

</div>

  • Related