JS: this (binding) in event handler

By Xah Lee. Date: . Last updated: .

for example:

const xx = document.getElementById("DttBX");

xx.addEventListener("click", function () {
 this.style.color = "red";
});

the value of this in a event handler is the element that fired the event.

you shouldn't use it. A better way is to use the event target. Every event handler is passed a event object. The element that fired the event is the value of the “target” property of the event object.

For example, do this:

const xx = document.getElementById("DttBX");
xx.addEventListener("click", (xevent) => {
 xevent.target.style.color = "red";
});