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

121
Visualizações
I am facing Loop issue in DOM Manipulation, Can anyone look at it please?

I am trying to make rainbow text but I am unable to loop over, can anyone help?

This is the HTML

<body>
    <h1>
        <span>R</span>
        <span>A</span>
        <span>I</span>
        <span>N</span>
        <span>B</span>
        <span>O</span>
        <span>W</span>
    </h1>
</body>```

And this is the javascript

const colors = ['red', 'orange', 'yellow', 'green', 'blue', 'indigo', 'violet']

I want to loop colors over the span using document.querySelectorAll

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

I'm not entirely sure what you're hoping to accomplish here. I think you want to color the individual letters with the elements in your colors array sequentially.

You can do that in several different ways. One of the more straightforward solutions would be to execute a callback function on an (array-like) nodelist using the forEach method.

Something like this...

  1. Gather your spans into a nodelist (using querySelectorAll)
  2. Iterate over the members of that nodelist (passing in the member variable and the index property)
  3. Assign an inline style (the color corresponding to the index in the colors array) in your callback function.

Or, you could add a class instead and probably others things as well.

Good luck.

const letters = document.querySelectorAll('.letters span');
const colors = ['red', 'orange', 'yellow', 'green', 'blue', 'indigo', 'violet'];

letters.forEach((letter, index) => {
  letter.style.color = colors[index]
})
<body>
  <h1 class="letters">
    <span>R</span>
    <span>A</span>
    <span>I</span>
    <span>N</span>
    <span>B</span>
    <span>O</span>
    <span>W</span>
  </h1>
</body>

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