0

I'd like to make a repeat pattern to color background. But after i is over colors.length it starts not to change background color because for example colors[3] does not exists. But I'd like to make colors[i] return back 0 again until first for loop completed.

const arr = document.getElementById('collection');
const colors = ['#FFC6C6', '#A4BDFF', '#F9F9F9'];

for (let i = 0; i < arr.children.length; i++) {
    arr.children[i].style.background = colors[i];
}

1 Answer 1

5

Read about modulo

const arr = document.getElementById('collection');
const colors = ['#FFC6C6', '#A4BDFF', '#F9F9F9'];

for (let i = 0; i < arr.children.length; i++) {
    arr.children[i].style.background = colors[i % colors.length];
}
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.