Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

177
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda