.each () terminate when the div is closed

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 run the columns with the .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 the first grid-f was closed in the given example, 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 the index 4 and not 0 as I wanted.

    
asked by anonymous 04.02.2016 / 14:16

1 answer

2

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 without distinction of their containers. With two loops, you'll cycle each%% of% separately.

    
04.02.2016 / 14:21