jquery – .each() terminates when div is closed

Question:

I have the following problem, I have divs that have a dynamic amount of divs inside.

<div class="grid-f">
  <div class="col-4"></div>
  <div class="col-4"></div>
  <div class="col-4"></div>
  <div class="col-4"></div>
</div>

<div class="grid-f">
  <div class="col-4"></div>
  <div class="col-4"></div>
  <div class="col-4"></div>
</div>

<div class="grid-f">
  <div class="col-4"></div>
  <div class="col-4"></div>
  <div class="col-4"></div>
</div>

I step through the columns with .each() and add classes every 3 divs

$('.col-4').each(function(index,value){
        if((index%3)==0){
            $(this).addClass('margin-r');
        } else if ((index%3)==1) {
            $(this).addClass('margin-lr');
        }
        else if ((index%3)==2) {
            $(this).addClass('margin-l');
        }
    });

But what I wanted was for .each() to stop when closing the first grid-f in the example given, because when it arrives at the first col-4 of the second grid-f it adds the wrong class because it understands that it is in index 4 and not at 0 like I wanted.

Answer:

You will need to use 2 .each to get the expected result.

$('.grid-f).each(function(index,value){
     jQuery(this).find('.col-4').each(function(index,value) {
        if((index%3)==0){
            $(this).addClass('margin-r');
        } else if ((index%3)==1) {
            $(this).addClass('margin-lr');
        }
        else if ((index%3)==2) {
            $(this).addClass('margin-l');
        }
     }
});

The problem you report occurs because the col-4 selector will select all elements regardless of their containers. With two loops, you'll grid-f through each grid-f separately.

Scroll to Top