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!

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 Select a Page Element By Its ID

Why can you not use the 'this' keyword within the event listener to reference the clicked element?

In the video an event listener is added to the title variable, and then the function references the 'title.style.color' - why can this reference not be 'this.style.color' if 'this' would capture the clicked element? i.e:

const title = document.getElementById('myHeading');

title.addEventListener('click', () => {
       this.style.color = 'red';  

2 Answers

Steven Parker
Steven Parker
228,026 Points

Using "this" within an event handler requires the handler to be defined with a conventional function declaration. It cannot be used when the function is defined with an arrow function, since one of the ways they are different from conventional functions is that they do not define "this".

An alternate way to access the event target that works with both kinds of functions is to pass in the event object and reference the "target" property:

title.addEventListener('click', e => {
    e.target.style.color = 'red';  

For more details on the function differences, see the MDN page on Arrow Functions.

Cheers Steven Parker, that makes sense now