Reputation: 49
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>
Upvotes: 0
Views: 63
Reputation: 148
look at your for loop... every item in h1 is being assigned the same color because they are all being run on the same for loop (iterating through all i values 0-6 therefore setting all items in h1 to the color violet).
try this instead...
const colors = ['red', 'orange', 'yellow', 'green', 'blue', 'indigo', 'violet'];
const spans = document.querySelectorAll('h1 span');
let count = 0;
for (let rain in rainbows) {
rain.style.color = colors[count];
count += 1;
}
Upvotes: 0
Reputation: 17524
You need to loop through span
s not the h1
, and get the corresponding index
for each span
in the color
array.
const colors = ['red', 'orange', 'yellow', 'green', 'blue', 'indigo', 'violet'];
const rainbow = document.querySelectorAll('span');
rainbow.forEach((rain, 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>
Upvotes: 0
Reputation:
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;
span
inside the h1
i
variable to 0
i
by 1Upvotes: 0
Reputation: 63550
If you use querySelectorAll
to also pick up the spans you can iterate over them (no need for a nested loop), and apply the colour to each one.
const colors = ['red', 'orange', 'yellow', 'green', 'blue', 'indigo', 'violet'];
const spans = document.querySelectorAll('h1 span');
for (let i = 0; i < spans.length; i++) {
spans[i].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>
Upvotes: 1