JavaScript JavaScript and the DOM Getting a Handle on the DOM Select a Page Element By Its ID

Lee Fendley
Lee Fendley
3,006 Points

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
203,722 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.

Lee Fendley
Lee Fendley
3,006 Points

Cheers Steven Parker, that makes sense now