I need help using javaScript to iterate over this h1, giving each span a different color from an array. I tried this, but its giving every span the last color in the array.
const colors = ['red', 'orange', 'yellow', 'green', 'blue', 'indigo', 'violet'];
const rainbow = document.querySelectorAll('h1');
for (let rain of rainbow) {
for (let i = 0; i < colors.length; i++) {
rain.style.color = colors[i];
}
}
<h1>
<span>R</span>
<span>A</span>
<span>I</span>
<span>N</span>
<span>B</span>
<span>O</span>
<span>W</span>
</h1>
>Solution :
You are very close, the issue you have is that you are looping every h1, not the span within, you are also looping inside this, so, with the following code;
const colors = ['red', 'orange', 'yellow', 'green', 'blue', 'indigo', 'violet'];
const rainbow = document.querySelectorAll('h1 span');
i = 0;
for (let rain of rainbow) {
rain.style.color = colors[i];
i++;
}
<h1>
<span>R</span>
<span>A</span>
<span>I</span>
<span>N</span>
<span>B</span>
<span>O</span>
<span>W</span>
</h1>
You can see this working. What this does is the following;
- Get every
spaninside theh1 - Set a
ivariable to0 - For every span, add a color, then increment
iby 1