user1448731 user1448731 - 7 months ago 8
Javascript Question

How to iterate a unique class in jQuery?

I have this list,

<ul id="list">
<li>Item 1</li>
<li>Item 2</li>
<li>Item 3</li>
<li>Item 4</li>
<li>Item 5</li>
<li>Item 6</li>
</ul>


And I want to dynamically add a class to it and will result to something like this,

<ul id="list">
<li class="class-1">Item 1</li>
<li class="class-2">Item 2</li>
<li class="class-3">Item 3</li>
<li class="class-4">Item 4</li>
<li class="class-1">Item 5</li>
<li class="class-2">Item 6</li>
</ul>


Here's my initial code,

jQuery(function(){
var list = jQuery('#list').children('li');
var arr = ['class-1','class-2','class-3','class-4'];
jQuery.each(arr, function(index, el) {
list.addClass(el);
});
});


But all it did is to add all the classes on each list item. I guess I really don't know what I'm doing here. I'd really appreciate if someone can point me in the right direction.

Answer

Please iterate over your list than array... You can try this code

jQuery(function(){
  var list = jQuery('#list').children('li');
  var arr = ['class-1','class-2','class-3','class-4'];

  list.each(function(index, el) {
      $(el).addClass(arr[index % arr.length]);
  });

});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<ul id="list">
<li>Item 1</li>
<li>Item 2</li>
<li>Item 3</li>
<li>Item 4</li>
<li>Item 5</li>
<li>Item 6</li>
</ul>

Comments