3

my html

<div id="mainMenu">
    <span>Thing 1</span>
    <span>Thing 2</span>
    <span>Thing 3</span>
    <span>Thing 4</span>
    <span>Thing 5</span>
    <span>Thing 6</span>
    <span>Thing 7</span>
</div>

how can i get thing 6 and thing 7 to have colors? it stops at them because it does 1-5

colors = ['red','orange','yellow','green', 'blue']; //roygbiv

$('#mainMenu span').each(function(i){
    this.style.color = colors[i];
});

1 Answers1

3

Let it wrap around:

this.style.color = colors[i % colors.length];

The expression i % colors.length yields the remainder after division of both operands and will always be in the range of [0, colors.length). It's also referred to as the modulo operator.

An even neater version can be made:

$('#mainMenu span').css('color', function(index) {
    return colors[index % colors.length];
});

Demo

See also:

Community
  • 1
  • 1
Ja͢ck
  • 161,074
  • 33
  • 239
  • 294