Lukas Niestrat
Lukas Niestrat

Reputation: 755

jQuery divide elements and add class

I want to count my li-elements in my navigation and divide them into four classes to get them an individual border-color.

It should look like:

<ul>
    <li class="red"></li>
    <li class="yellow"></li>
    <li class="green"></li>
    <li class="blue"></li>
    <li class="red"></li>
    <li class="yellow"></li>
    <li class="green"></li>
    <li class="blue"></li>
</ul>

Of course I want it dynamically with jQuery.

I've tried:

$('#navbar li').each(function(i) {
    $(this).addClass('className-' + i);
});

but that code count all li-elements in my ul..

Thank for help!

Upvotes: 1

Views: 246

Answers (1)

Ankit Chaudhary
Ankit Chaudhary

Reputation: 4089

You can store those Classes in an array & assign a class to each li element based on the remainder of element's index when divided by 4 (i%4).

var classNames=['red','yellow','green','blue'];
$('li').each(function(i) {
    $(this).addClass(classNames[i%4]);
});
.red{
  color:red;
  }
.yellow{
  color:yellow;
  }
.green{
  color:green;
  }
.blue{
  color:blue;
  }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul>
    <li>One</li>
    <li>Two</li>
    <li>Three</li>
    <li>Four</li>
    <li>Five</li>
    <li>Six</li>
    <li>Seven</li>
    <li>Eight</li>
  <li>Nine</li>
    <li>Ten</li>
</ul>

Upvotes: 1

Related Questions