Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

176
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda