Geoff
Geoff

Reputation: 199

jQuery class increment on divs

I have 4 tabbed content boxes, each with anywhere from 1 to 6 divs within like so:

<div id="tab-1" class="tab-content current">
   <div class="tabbedProduct">
   </div>
   <div class="tabbedProduct">
   </div>
   <div class="tabbedProduct">
   </div>
</div>

<div id="tab-2" class="tab-content">
   <div class="tabbedProduct">
   </div>
   <div class="tabbedProduct">
   </div>
   <div class="tabbedProduct">
   </div>
</div>

I'm then using jQuery to add an incremental number to each .tabbedProduct div within the .tab-content div so for instance:

<div id="tab-1" class="tab-content current">
   <div class="tabbedProduct item1">
   </div>
   <div class="tabbedProduct item2">
   </div>
   <div class="tabbedProduct item3">
   </div>
</div>

Of course I need the counters to start from 1 within each .tab-content div so in this instance the .tab-content div with the id of #tab-1 would count to .tabbedProduct item3 by the end.

My issue is, that the jQuery I have is continuing to count through the other .tab-content divs and so in the above instance the first .tabbedProduct div would have a item4 added but I need the counter to start again so it would be item1 to item 3 as per the first.

Here is the jQuery I have if anyone can help thanks very much.

$('.tab-content .tabbedProduct').each(function(i) {
    $(this).addClass('item' + (i+1));
});

Happy New Year BTW :)

Upvotes: 3

Views: 762

Answers (2)

adeneo
adeneo

Reputation: 318372

Should be straight forward with a callback and index

$('.tabbedProduct').addClass(function() {
    return 'item' + ($(this).index()+1);
});

Upvotes: 0

void
void

Reputation: 36703

$('.tab-content').each(function() {
  $(this).find('.tabbedProduct').each(function(el) {
    $(this).addClass('item' + (el + 1));
  });
});

You need to iterate across .tab-content and inside that iterate among .tabbedProduct and add the class, this way el will always initiate with 0 again for every .tab-content.

Upvotes: 4

Related Questions