Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

JavaScript

varlevi
varlevi
8,113 Points

Changing the Text Color of all items with the same tag in Javascript

Hi! I need to change the color of all h3 elements on a page when the user clicks a button in vanilla javascript. I've tried loop through an array with all the h3 in it using for loops, but I'm getting an

Uncaught TypeError: Cannot read property 'style' of undefined
    at HTMLDivElement.<anonymous>

error. Here's my code:

let darkButton = document.getElementById('dark-button');
darkModeState = false;
darkButton.addEventListener('click', () => {
  darkModeState = !darkModeState;
  let h3 = document.getElementsByTagName('H3');
  if (darkModeState == true) {
    document.body.style.backgroundColor = "#111";
    document.getElementsByTagName('h1')[0].style.color = '#DDD';
    document.getElementsByTagName('h2')[0].style.color = '#DDD';
    for (i of h3) {
      h3[i].style.color = '#DDD';
    }
  } else {
    document.body.style.backgroundColor = "#FFF";
    document.getElementsByTagName('h1')[0].style.color = '#DDD';
    document.getElementsByTagName('h2')[0].style.color = '#DDD';
    for (i of h3) {
      h3[i].style.color = '#DDD';
    }
  }
})

Thanks in advance for any help!

2 Answers

varlevi So when you're using the for of loop, the "i" in the "i of h3" is already referencing the specific iteration of the h3 elements that you're looping through, so rather than using h3[i].style.color you would just use i.style.color! I hope this helps! if not, let me know!

Steven Parker
Steven Parker
216,057 Points

To iterate on the indexes, use "in". Using "of" iterates on the elements themselves as Ryan mentioned.

    for (i in h3) {