user1469270
user1469270

Reputation:

Loop through multiple arrays

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?

JSFIDDLE

Upvotes: 0

Views: 624

Answers (1)

Joseph Silber
Joseph Silber

Reputation: 219938

Use the % modulus operator:

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

Related Questions