I'm doing The Web Developer Bootcamp by Colt Steele and got stuck on a challenge.
My task is to select all spans, iterate over them and assign each one of the colors from the colors array.
My solution is:
const colors = ['red', 'orange', 'yellow', 'green', 'blue', 'indigo', 'violet']; //PLEASE DON'T CHANGE THIS LINE!
//YOU CODE GOES HERE:
const lettersList = document.querySelectorAll('span');
for (let i = 0; i < colors.length; i++){
lettersList.forEach((letter) => {
letter.style.color = "colors[i]";
});
}
My idea is to use a for loop to iterate the values of the colors array (stop the loop upon reaching the last element).
Nested inside the for loop is the forEach function that will execute the function letter.style.color = "colors[i]" that will assign the value of the iterated colors array to each value of the selectorAll span.
Can you spot my mistake?
"colors[i]" is a string that will not be interpretted by javascript. Remove the quotes. Also, you don't need both loops. You can access the index in your forEach loop as the second argument:
lettersList.forEach((letter, i) => {
letter.style.color = colors[i];
});
Here's a snippet that demonstrates - also taking into account that your array of colors might not be the same length as the number of spans.
const colors = ['red', 'orange', 'yellow', 'green', 'blue', 'indigo', 'violet']; //PLEASE DON'T CHANGE THIS LINE!
//YOU CODE GOES HERE:
const lettersList = document.querySelectorAll('span');
lettersList.forEach((letter, i) => {
let index = i < colors.length ? i : i % colors.length
console.log(index)
letter.style.color = colors[index];
});
span {
display: inline-block;
padding: 10px;
}
<span>Color me</span>
<span>Color me</span>
<span>Color me</span>
<span>Color me</span>
<span>Color me</span>
<span>Color me</span>
<span>Color me</span>
<span>Color me</span>
<span>Color me</span>
<span>Color me</span>