Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

175
Views
Selecting all spans and assigning a style.color value from an array usingn DOM selector

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?

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

"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>

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!