0

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

1 Answer 1

5

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/

Sign up to request clarification or add additional context in comments.

3 Comments

It should be i % colorsCount actually.
Thanks, can you explain the logic to that?
@tmyie - i % colorsCount will divide i by colorsCount, and return the remainder. As long as i is less than colorsCount, you'll always get back i. If i is greater than colorsCount, you'll get i - colorsCount (as many times as possible).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.