treehouse : what would you like to learn today?
Web Design Web Development iOS Development

AddClass "1" to "6" then repeat after six list items jQuery

  • I want to add a left border color on my vertical navigation with each list item is a different colour so i thought about adding a incremented class name that starts to repeat after 6 list items.


    <li class="1"></li>
    <li class="2"></li>
    <li class="3"></li>
    <li class="4"></li>
    <li class="5"></li>
    <li class="6"></li>
    <li class="1"></li>
    <li class="2"></li>


    Can you help me try to accomplish this effect.

    Thanks for any suggestions
  • I haven't tested it but something like this should do the trick right?:

     var i = 0;
    $('ul').find('li').each(function(){
    if(i<6){
    i++;
    }
    else{
    i = 1;
    }
    $(this).addClass('class-' + i);
    });


    You might need to tweak it a bit but you get the idea.
  • Cheers perfect!
  • Here is another version of Johnnyb's code (demo):
    $('ul').find('li').each(function(i){
    var num = (i%6) + 1; // mod function - returns the remainder
    $(this)
    .addClass('class-' + num )
    .html('item ' + num);
    });

  • you could just use css nth-child to target the list items. of course IE won't honor that, but give it a fallback color and IE users be damned.