Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

JavaScript JavaScript and the DOM (Retiring) Getting a Handle on the DOM A Simple Example

Abhijit Das
Abhijit Das
5,022 Points

why the heading element color isn't changing on mouse click?

Hello, I am trying to change all heading color at once. When I am using document.addEventListener handle heading colors are changing, however by using variable name the heading color isn't changing. Pls let me know why it's happening? can't we use event handler on array object? code is here : https://codepen.io/anon/pen/pwwKzE

1 Answer

Jennifer Nordell
seal-mask
STAFF
.a{fill-rule:evenodd;}techdegree
Jennifer Nordell
Treehouse Teacher

Hi there! You can only add an event listener to one item at a time. But you're trying to add an event listener to an array of elements. Now you could put an event listener on the document or you could select a specific element to put that event listener on. I chose the document as the element. Whenever you click anywhere on the document it changes the color of the text.

Here's what I did:

const headingTwo = document.getElementsByTagName('h2');
document.addEventListener ('click',() => {
  for(i = 0; i < headingTwo.length; i++) {
  headingTwo[i].style.color = "olive";
  }
})

Hope this helps! :sparkles:

Abhijit Das
Abhijit Das
5,022 Points

Thank you Jennifer, yes i understand it. Later i modified the code little bit as follow below. Where if i click on the first heading all heading color will be changed.

const headingTwo = document.getElementsByTagName('h2');
headingTwo[0].addEventListener ('click',() => {
  for(i = 0; i < headingTwo.length; i++) {
  headingTwo[i].style.color = "olive";
  }
})