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
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...
querySelectorAll)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>