JS: What's the Value of “this” in Event Handler?

By Xah Lee. Date: . Last updated: .

for example:

const myEle = document. getElementById("xyz");
myEle.addEventListener ("click", function () { this.style.color = "red"; }, false)

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 myEle = document. getElementById("xyz");
myEle.addEventListener ("click", ((evt) => { evt.target.style.color = "red";}) , false)

See also: JS: “this” Binding

DOM How-To


Web Scripting Overview


HTML Input


Web Scripting Examples


Web Scripting Misc


jQuery


node.js

Like it? Help me by telling your friends. Or, Put $5 at patreon.

Or, Buy JavaScript in Depth

If you have a question, put $5 at patreon and message me.

Web Dev Tutorials