Is the "this" value in a DOM event handler bound to any "EventTarget" rather than only to DOM elements?

I was reading the MDN documentation on this in DOM event handlers which states:

When a function is used as an event handler, its this parameter is bound to the DOM element on which the listener is placed.

However, in practice this seems to be slightly misleading, because the listener’s this is actually bound to whatever EventTarget you attached it to—even if it isn’t an HTML element. For example:

// 'document' is not an Element node, but an EventTarget
document.addEventListener('visibilitychange', function() {
  // `this` === document
  console.log(this.hidden, document.hidden); // both true/false
});

Here, inside the handler, this.hidden behaves exactly like document.hidden. Similarly, if I do:

window.addEventListener('resize', function() {
  console.log(this === window); // true
});

…the same principle applies: this is the EventTarget (in this case, window), not necessarily a DOM Element.


  1. Is the MDN wording inaccurate or just informal?
  2. What is the precise specification language for what this refers to in an event listener callback?
  3. Should MDN’s phrasing be updated to mention “EventTarget” rather than “DOM element”?

Before I edit the MDN article, I need to make sure it really needs improvement.

Any references to the DOM/EventTarget spec or other authoritative sources would be greatly appreciated!

I believe you are correct.

Inside an event listener this refers to the object the listener is attached to, which can be any EventTarget and not just a DOM element. This behavior is detailed in the DOM Level 2 Events Specification, section 1.3.2:

The DOM Event Model allows registration of multiple event listeners on a single EventTarget.

This shows that event listeners aren’t limited to DOM elements—they can be attached to any object that implements the EventTarget interface, including things like document and window.

That said, I still find “DOM element” easier to understand in casual docs, even if it’s technically not 100% correct. I suppose one could say:

Inside an event listener, this refers to the object the listener was attached to—typically a DOM element, but more generally any object that implements the EventTarget interface, such as document or window.

But that’s quite verbose, so I dunno …
¯_(ツ)_/¯

1 Like

“DOM element” != an Element class object.

The DOM contains more than Elements (proper noun); but those things are elements (common noun) of the DOM.

Confusing wording? Yes. But not the same thing.