Home > Mobile >  How to make a repeat pattern in for loop Javascript?
How to make a repeat pattern in for loop Javascript?

Time:08-18

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];
}

CodePudding user response:

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];
}
  • Related