liveBook · Manning

Event target

As explained in Secrets of the JavaScript Ninja, Second Edition

The object or element on which an event originally occurred and which is exposed through the event object's target reference.

An event’s target is the element where it originated, available as event.target in the event object. As the event propagates through nested elements, handlers on different elements can see the same target; this differs from this, which refers to the element where a handler is registered. section 13.3 section 13.3.1

A click inside nested elements

If a click originates on an inner container, both its handler and the outer container’s handler see the inner container as event.target. The outer handler’s this refers to the outer container. section 13.3.1

Listing 13.9. The difference between this and event.target in event handlers
const outerContainer = document.getElementById("outerContainer");
const innerContainer = document.getElementById("innerContainer");

innerContainer.addEventListener("click", function(event){ 
  report("innerContainer handler");                                 #A
  assert(this === innerContainer,                                   #A
         "This referes to the innerContainer");                     #A
  assert(event.target === innerContainer,                           #A
         "event.target refers to the innerContainer");              #A
});

outerContainer.addEventListener("click", function(event){
  report("innerContainer handler");                                 #B
  assert(this === outerContainer,                                   #B
         "This refers to the outerContainer");                      #B
  assert(event.target === innerContainer,                           #B
         "event.target refers to the innerContainer");              #B
});

Compare this and event.target in handlers registered on nested elements. section 13.3.1

How Secrets of the JavaScript Ninja, Second Edition covers it

How deep it goes
Defines event.target and contrasts it with this during capturing and bubbling.
Examples
Uses a button click and nested-container click handlers to distinguish the target from the handler element.
What it assumes
Assumes familiarity with DOM elements, event handlers, and addEventListener.
What you can do after
Understand which element originated an event and distinguish it from the element handling the event.
How it connects
Connects event.target to event handlers, addEventListener, and DOM event propagation.

Also explained in

Compare how 3 books explain event target →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Secrets of the JavaScript Ninja, Second Edition. The section links point to the parts of the book it draws on.