Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Iterating h1 using js

I need help using javaScript to iterate over this h1, giving each span a different color from an array. I tried this, but its giving every span the last color in the array.

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

const rainbow = document.querySelectorAll('h1');

for (let rain of rainbow) {
  for (let i = 0; i < colors.length; i++) {
    rain.style.color = colors[i];
  }
}
<h1>
  <span>R</span>
  <span>A</span>
  <span>I</span>
  <span>N</span>
  <span>B</span>
  <span>O</span>
  <span>W</span>
</h1>

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

You are very close, the issue you have is that you are looping every h1, not the span within, you are also looping inside this, so, with the following code;

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

const rainbow = document.querySelectorAll('h1 span');
i = 0;
for (let rain of rainbow) {
  rain.style.color = colors[i];
  i++;
}
<h1>
  <span>R</span>
  <span>A</span>
  <span>I</span>
  <span>N</span>
  <span>B</span>
  <span>O</span>
  <span>W</span>
</h1>

You can see this working. What this does is the following;

  • Get every span inside the h1
  • Set a i variable to 0
  • For every span, add a color, then increment i by 1
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading