.each() ends when the div is closed

Asked

Viewed 26 times

3

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 scroll 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 it closed the first grid-f in the example given, because when you arrive at the first col-4 of the second grid-f it adds the wrong class because it understands that it is at index 4 and not at 0 as I wanted.

1 answer

2


You will need to use 2 .each to obtain 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 selector col-4 will select all elements without distinction of their containers. With two loops, you will traverse each grid-f separately.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.