Danny Englander
Danny Englander

Reputation: 2044

jQuery add class numericly up to x and start over

With jQuery I can add consecutive numeric classes to list items like so:

  $(".item-list li").each(function (i) {
      $(this).addClass("item-list-" + i);
   });

So with an HTML structure as such:

<ul class="item-list">
  <li>an item</li>
  <li>another item</li>
  <li>another item</li>
  <li>another item</li>
  <li>another item</li>
</ul>

... this will output nice list item classes in numeric order:

class="item-list-0"
class="item-list-1"

... etc...

What I'm trying to do is number of to 4 items and then start the numbering over at zero again. I figured I'd have to use nth child within my numeric + i code but I just have not been able to find any documentation on this. Everything that I've found relates to finding an nth element but not starting a count over after a specified amount.

Upvotes: 0

Views: 160

Answers (1)

PSL
PSL

Reputation: 123739

you can do this using modulus operator itself:

$(".item-list li").each(function (i) {
    $(this).addClass("item-list-" + (i%4));
});

Output markup

<ul class="item-list">
    <li class="item-list-0">an item</li>
    <li class="item-list-1">another item</li>
    <li class="item-list-2">another item</li>
    <li class="item-list-3">another item</li>
    <li class="item-list-0">another item</li>
    <li class="item-list-1">another item</li>
    <li class="item-list-2">another item</li>
    <li class="item-list-3">another item</li>
    <li class="item-list-0">another item</li>
</ul>

Demo

Upvotes: 2

Related Questions