Reputation:
I'm trying to loop through a series of li
elements, and match each element with a color from the color
array, like so:
var li = document.getElementsByTagName('li');
var colors = ["salmon", "teal", "orange", "grey", "blue"];
for (i=0; i < li.length; i++) {
li[i].style.backgroundColor=colors[i]
}
However, because the length of colours are shorter than the length of the li elements, it stops short.
How can I make the colours array loop through again, until it matches whatever the number of li elements there are?
Upvotes: 0
Views: 624
Reputation: 219938
var li = document.getElementsByTagName('li');
var colors = ["salmon", "teal", "orange", "grey", "blue"];
var colorsCount = colors.length;
for ( var i = 0; i < li.length; i++ ) {
li[i].style.backgroundColor = colors[ i % colorsCount ];
}
Here's your fiddle: http://jsfiddle.net/LhmgQ/1/
Upvotes: 5