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];
});
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:
css(propertyName, function(index,value))If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With