completefrontend
Open lab My progress
THE WEB COMPONENTS FIELD GUIDE

Event retargeting

Learn shadow DOM event retargeting: why event.target shows the host, what each listener sees, and how composedPath() finds the element clicked.

By the end, you can
  • 01
    Say what each listener readsTell what event.target is inside a shadow root, on its host, and on the page, even with components inside components.
  • 02
    Use the retarget ruleWalk the DOM Standard's rule by hand, and explain why a slotted element stays the target.
  • 03
    Find the real elementRead composedPath() while the event runs, know what a closed root leaves out, and fix page-wide delegation.

What is event retargeting?

Leaf and Kettle's menu page has a small script that counts clicks. It listens on the whole page and writes down what was clicked. Asha clicks Add Oolong on a tea card. The log says tea-card. Ravi expected button.

You met this in lesson 2.2, lesson 5.3, and lesson 6.3. Outside a shadow root, a click seems to come from the host. But who sees the button, and who sees the card? And how can the page find the real button?

Event retargeting means the browser changes event.target for each listener. A listener inside a shadow root reads the element that was clicked. A listener outside it reads the host, the element the shadow root belongs to.

A click starts at the element under the pointer and travels up through its parents. Bubbling and capturing explains that trip. Here is one click, heard in four places:

One click, heard in four placesPop out in the code editor (opens in a new tab)HTML
<tea-card></tea-card> <script src="tea-card.js"></script><script>  const card = document.querySelector("tea-card");  card.addEventListener("click", (event) => {    console.log("Card:", event.target.localName);  });  document.addEventListener("click", (event) => {    console.log("Document:", event.target.localName);  });  window.addEventListener("click", (event) => {    console.log("Window:", event.target.localName);  });</script>
ResultLoading…
  • In the tea-card.js tab, line 5 puts a button in the card's shadow root. Lines 6 to 8 listen inside the root. localName is the tag name in lowercase.
  • On the page, line 5 finds the card, the host. Lines 6 to 8 listen on it.
  • Lines 9 to 11 listen on document. Lines 12 to 14 listen on window.

Click Add Oolong. The console prints four lines: Root: button, Card: tea-card, Document: tea-card, and Window: tea-card. One click, two answers. Even the card's own listener reads tea-card. Only the listener inside the root sees the button.

One click on Add Oolong, four listeners. A listener on the shadow root reads button. A listener on the tea-card reads tea-card. A listener on the document reads tea-card. A listener on the window reads tea-card. A dashed line separates the shadow root from the rest.where the listener isshadow rootbuttontea-cardtea-carddocumenttea-cardwindowtea-cardevent.target it readsinside the rootoutside the root
One click on Add Oolong. The listener inside the shadow root reads the button. Every listener outside it, even the one on tea-card itself, reads tea-card.
Real-life analogyPhoning the tea shop

You phone Leaf and Kettle. Someone picks up and says "Leaf and Kettle, hello". You get your answer, but you never learn which barista picked up. The staff in the shop know it was Ravi.

In real life: The barista who picks up
In JavaScript: The button inside the shadow root
In real life: "Leaf and Kettle, hello"
In JavaScript: The host, tea-card, as the target
In real life: You, the caller
In JavaScript: A listener outside, like document
In real life: The staff in the shop
In JavaScript: A listener inside the shadow root
The main idea

The browser gives every listener its own event.target. Inside the shadow root, it's the element that was clicked. Outside, it's the host. The event itself still reaches every listener on its path.

Why it matters: the page never depends on what's inside the card. The card could swap its button for a link tomorrow. The page would still read tea-card.

This lesson follows that click along its whole path. First, what each listener reads. Then the rule the browser follows, slots, and composedPath(). Then closed roots, and a common bug on real sites.

What does event.target show inside and outside a shadow root?

A click makes two trips. First it goes down from the window to the button. That's the capture phase. Then it bubbles back up. A listener can run on either trip. Does the target depend on the trip?

Listening on the way down, and on the hostPop out in the code editor (opens in a new tab)HTML
<tea-card></tea-card> <script src="tea-card.js"></script><script>  document.addEventListener("click", (event) => {    console.log("Document, on the way down:", event.target.localName);  }, { capture: true });  const card = document.querySelector("tea-card");  card.addEventListener("click", (event) => {    console.log("Card, phase:", event.eventPhase);  });</script>
ResultLoading…
  • Lines 5 to 7 listen on document with { capture: true }. That listener runs on the way down, before any other.
  • Lines 9 to 11 listen on the card and print event.eventPhase. That number says where the event is: 1 on the way down, 2 at the target, and 3 on the way up.
  • The tea-card.js tab is the card from the first example. Its root prints Root: and the target.

Click Add Oolong. The console prints Document, on the way down: tea-card, then Root: button, then Card, phase: 2.

Look at the first line. The event hadn't reached the button yet, and the target was already tea-card. So the target doesn't change at the moment the event leaves the root. Each listener simply gets its own view, on the way down and on the way up.

Now the last line. Phase 2 means "at the target". To the card, the click happened on the card itself. The DOM Standard marks the host as a target on the event's path, so its listeners run at phase 2. The click can get this far because it's composed: it may cross out of a shadow root. MDN says every click the browser sends is composed.

So who reads what? Two rules cover the single root:

  • A listener in the same tree as the button reads the button. That's any node in the shadow root, or the root itself.
  • A listener anywhere else reads the host. That's the host itself, its parents, document, and window.

Every listener can also read event.currentTarget, the node it was added to. On the card, both are tea-card.

Why it matters: a component that needs to know which of its own buttons was pressed listens on its shadow root. In the class, this.addEventListener() listens on the host, so it reads the host. this.shadowRoot.addEventListener() reads the button.

How does the browser pick the target for each listener?

With one shadow root, the answer is inside or outside. But components hold other components. The kit's tea-panel from lesson 8.3 keeps a tea-card in its shadow root. The card has a shadow root of its own. So where does a click on the card's Tasting notes heading come from?

Three trees, three listenersPop out in the code editor (opens in a new tab)HTML
<tea-panel>  <span slot="heading">Oolong</span>  <p>Floral</p></tea-panel> <script type="module">  import "./tea-kit/index.js";   const panel = document.querySelector("tea-panel");  const card = panel.shadowRoot.querySelector("tea-card");  function show(where, event) {    console.log(`${where}: ${event.target.localName}`);  }  card.shadowRoot.addEventListener("click", (event) => show("Card's root", event));  panel.shadowRoot.addEventListener("click", (event) => show("Panel's root", event));  document.addEventListener("click", (event) => show("Document", event));</script>
ResultLoading…
  • Lines 1 to 4 are the panel, with a name and one tasting note. Line 7 loads the kit.
  • Line 9 finds the panel. Line 10 finds the card inside the panel's shadow root.
  • Lines 11 to 13 print where a listener is, and the target it reads.
  • Lines 14 to 16 listen in three trees: the card's root, the panel's root, and the page.

Click Tasting notes. The console prints Card's root: h4, Panel's root: tea-card, and Document: tea-panel. Three listeners, three answers. Each one reads the nearest node it can see.

Now click Today's special, the panel's own label. Two lines print: Panel's root: p and Document: tea-panel. The card's root stays quiet. The label isn't inside the card, so the click never passes through it.

Three windows, one inside the other: the page, the panel's root, and the card's root, which holds the h4 Tasting notes. Arrows lead from each to what a listener there reads: the card's root reads h4, the panel's root reads tea-card, and the page reads tea-panel.pagepanel's rootcard's root<h4> Tasting notesa listener there readstea-paneltea-cardh4
One click on Tasting notes, three trees. A listener in the card's root reads h4. One in the panel's root reads tea-card, the nearest host it can see. One on the page reads tea-panel.
Real-life analogyEach desk logs the nearest name it knows

Leaf and Kettle runs a tea stall inside a food hall. Ravi sends a parcel from the stall. The stall's own book says "from Ravi". The food hall's office never sees inside the stall, so it writes "from the tea stall". The street's post office only knows the building: "from the food hall".

In real life: Ravi, who sent the parcel
In JavaScript: The h4 that was clicked
In real life: The tea stall
In JavaScript: tea-card, the inner host
In real life: The food hall
In JavaScript: tea-panel, the outer host
In real life: The desk at each level
In JavaScript: A listener in each tree
In real life: The nearest name that desk knows
In JavaScript: The target that listener reads

The rule in the DOM Standard

The DOM Standard writes the rule as a short algorithm called retarget. Spec steps read like a recipe. "Return A" means "the answer is A". "Set A to" means "A now stands for something else". Here it is:

Retarget A against B, from the DOM StandardText
To retarget an object A against an object B, repeat these steps until they return an object:
1. If one of the following is true, then return A:
   - A is not a node
   - A's root is not a shadow root
   - B is a node and A's root is a shadow-including inclusive ancestor of B
2. Set A to A's root's host.

In plain words, line by line:

  1. A starts as the node where the event began. B is the node the listener is on, its currentTarget. The steps repeat until one of them gives the answer.
  2. Step 1 has three ways to stop. Any one of them is enough.
  3. If A isn't a node, there's nothing to hide. Stop.
  4. A node's root is the top of its tree: the document for the page's own nodes, or a shadow root. If A's root isn't a shadow root, A is public. Stop.
  5. If B is inside A's root, B may see A. Stop. "Shadow-including inclusive ancestor" means B is in that tree, or inside a shadow root somewhere below it.
  6. Otherwise, A moves up to the host of its root. Then the steps start again.

The steps for dispatching an event give every listener this answer. A is the node the event started at, and B is the listener's own node. Pick a listener, and watch the rule walk the click on Tasting notes:

Playground: walk the retarget rule
The retarget rule, in plain wordsText
A = the node where the event started
B = the node the listener is on
repeat:
  if A's root is not a shadow root, the answer is A
  if B is inside A's root, the answer is A
  A = the host of A's root
Each pass through the loop
  1. A is h4. Its root is the card's shadow root. The card's shadow root is inside that root, so the answer is h4.
Try it yourself
In the card's root, the listener reads h4

The listener is in the same tree as the h4. Line 5 stops the loop on the first pass.

The click is on Tasting notes, the h4 in the card's shadow root, on the kit's tea-panel page above. A is where the event started. B is the node the listener is on.

Try On tea-panel. A host sits outside its own shadow root, just like the page. So A climbs past tea-card to tea-panel. Then try On window. The window isn't a node, so line 5 never stops the loop. It reads what document reads.

Why it matters: apps put components inside components, many levels deep. A listener never learns more than its own tree holds. Each component keeps its inside to itself. Firefox's own code, nsContentUtils::Retarget(), reads almost line for line like these steps.

Are slotted elements retargeted?

No. Look back at the panel. Floral was the page's own paragraph, shown through two slots: the panel's, then the card's. A click on it printed p three times. Nobody's view changed. Here is the same thing with one card:

A slotted span stays the targetPop out in the code editor (opens in a new tab)HTML
<tea-card>  <span slot="name">Oolong</span></tea-card> <script src="tea-card.js"></script><script>  document.addEventListener("click", (event) => {    console.log("Document:", event.target.localName);  });</script>
ResultLoading…
  • Line 2 is the page's span, sent to the card's name slot, as in lesson 8.1.
  • In the tea-card.js tab, line 5 puts an h3 with the name slot, and a button, in the shadow root. Lines 6 to 8 print what the root reads.
  • On the page, lines 7 to 9 print what the document reads.

Click Oolong. The console prints Root: span and Document: span. Then click Add. It prints Root: button and Document: tea-card.

The rule explains it. The span lives in the page's own tree, the light DOM, as lesson 8.2 showed. Its root is the document, not a shadow root. So the rule stops on line 4, on the first pass, for every listener. Nothing about the span is private. The page wrote it.

Real-life analogyYour own cup at the counter

Asha brings her own cup to Leaf and Kettle. Ravi fills it behind the counter. Ask anyone whose cup it is, staff or people in the queue. They all say the same thing: it's Asha's.

In real life: Asha's own cup
In JavaScript: The slotted span, written by the page
In real life: Being filled behind the counter
In JavaScript: Showing in a slot inside the shadow root
In real life: "Whose cup is it?"
In JavaScript: event.target
In real life: Everyone gives the same answer
In JavaScript: Every listener reads span

The click still travels through the slot. On the way up, a slotted node's parent is the slot it shows in. That's why the listener inside the root heard it at all. The next section shows the slot in the path.

Why it matters: a component can listen on itself and still learn which child was clicked. The kit's tea-picker from lesson 8.5 does this. It listens on the host, and event.target is the option button the page wrote.

What does composedPath() return?

event.target gives one node. Sometimes code needs more, like which button inside the card was pressed. event.composedPath() gives the whole route. It returns an array of every node the event visits. It starts where the event started and ends at window.

Reading the whole path on the pagePop out in the code editor (opens in a new tab)HTML
<tea-card></tea-card> <script src="tea-card.js"></script><script>  document.addEventListener("click", (event) => {    const path = event.composedPath();    const names = path.map((node) => node.localName ?? node.constructor.name);    console.log(names.join(", "));    console.log("Started at:", path[0].localName);    console.log("Target:", event.target.localName);  });</script>
ResultLoading…
  • Line 6 reads the path. It's a plain array.
  • Line 7 turns each node into a name. ?? means "if the left side is missing, use the right side". A shadow root, the document, and the window have no tag name, so their class name shows instead.
  • Line 9 prints the first stop, path[0]. Line 10 prints the target.

Click Add Oolong. Line 8 prints button, ShadowRoot, tea-card, body, html, HTMLDocument, Window. Line 9 prints Started at: button, but line 10 prints Target: tea-card. For an open root, the page's path still starts at the button. Lit's docs give this tip for finding where an event came from: read composedPath()[0].

Real-life analogyA tour guide's list of stops

On a tea tour, the guide carries a list of every stop. While the tour runs, anyone on the bus can read it. When the tour ends, the guide throws the list away. Ask for it the next morning, and you get a blank page.

In real life: Each stop on the tour
In JavaScript: Each node the event visits
In real life: The guide's list
In JavaScript: event.composedPath()
In real life: The first stop on the list
In JavaScript: composedPath()[0], where the event started
In real life: A blank list after the tour
In JavaScript: [] once the event is over

After the event is over

The path only exists while the event runs. What happens if you read it later?

The path, during the click and after itPop out in the code editor (opens in a new tab)HTML
<tea-card></tea-card> <script src="tea-card.js"></script><script>  document.addEventListener("click", (event) => {    console.log("During:", event.composedPath().length, event.target.localName);    setTimeout(() => {      console.log("After:", event.composedPath().length, event.target.localName);    });  });</script>
ResultLoading…
  • Line 6 prints the path's length and the target while the listener runs.
  • Lines 7 to 9 print the same two things in a timer, after the event is over.

The console prints During: 7 tea-card, then After: 0 tea-card. The DOM Standard empties the path once the event has visited every node. Chrome's composedPath() code gives an empty array whenever no listener is running. So copy what you need from the path inside the listener.

The target is still tea-card afterwards. It never turns into the button. But an event that never leaves the root ends differently:

An event that stays inside the rootPop out in the code editor (opens in a new tab)HTML
<tea-card></tea-card> <script src="tea-card.js"></script><script>  const card = document.querySelector("tea-card");  const button = card.shadowRoot.querySelector("button");  const check = new Event("tea-check", { bubbles: true });  button.dispatchEvent(check);  console.log(check.target, check.composedPath().length);</script>
ResultLoading…
  • Line 7 makes an event that bubbles but isn't composed. So it stays inside the shadow root, like the events in lesson 5.3.
  • Line 8 dispatches it on the button. dispatchEvent() runs every listener before it returns.
  • Line 9 prints the target and the path's length.

It prints null 0. Every target this event had was inside the shadow root. So once it's over, the DOM Standard sets target to null. A saved event can't leak a private node later.

Why it matters: read composedPath() and event.target while the listener runs. Copy what you need into a variable before any timer or await.

Old answers on the web use event.path or event.deepPath(). Both were Chrome-only. Chrome 50 to 52 called the method deepPath, and Chrome removed event.path in Chrome 109. Use composedPath().

What does a closed shadow root hide from composedPath()?

Lesson 6.2 showed the first part. With a closed root, the page's composedPath() starts at the host, not at the button. The target is tea-card in both modes. Retargeting doesn't depend on the mode. Only the path does.

But what about a slotted node in a closed root? The node is public, and the slot it passes through is private. Pick a mode below. Then click Add, and Oolong, in the result:

Playground: the event path explorer
A card with a slotted name and a buttonPop out in the code editor (opens in a new tab)HTML
<tea-card>  <span slot="name">Oolong</span></tea-card> <script src="report.js"></script><script>  class TeaCard extends HTMLElement {    constructor() {      super();      const root = this.attachShadow({ mode: "open" });      root.innerHTML = `<h3><slot name="name"></slot></h3><button>Add</button>`;      root.addEventListener("click", (event) => report("Root", event));    }  }  customElements.define("tea-card", TeaCard);  document.addEventListener("click", (event) => report("Page", event));</script>
ResultLoading…
Try it yourself
Both listeners get the whole path

Click Add. The root reads button and the page reads tea-card, but both paths start at the button. Click Oolong. Both read span, and the path passes through the slot, the h3, and the shadow root.

Only line 10 changes. Click Add, then Oolong, in the result. The report.js tab prints who heard the click, the target it read, and the whole path.
  • Line 10 is the only line that changes: the root's mode.
  • Line 12 listens inside the root. Line 16 listens on the page. Both call report().
  • In the report.js tab, line 2 names every stop on the path. Line 3 prints who heard the click, the target, and the path.

With an open root, both listeners get the same full path. Now pick Closed root and click Oolong. The page reads span, and its path is span, tea-card, body, html, HTMLDocument, Window. The span stays, because the page wrote it. But the slot, the h3, and the shadow root are cut out of the middle. Inside the root, line 12 still prints every stop.

Two rows of cards for one click on Oolong in a closed card. The listener inside the root sees: span, slot, h3, ShadowRoot, tea-card, body, html. The page's listener sees the same row, but slot, h3, and ShadowRoot are faded and crossed out, so its path goes from span straight to tea-card.the listener inside the closed root seesspansloth3ShadowRoottea-cardbodyhtmlthe page's listener seesspansloth3ShadowRoottea-cardbodyhtmlboth paths go on to HTMLDocument and Window
A closed card, and a click on Oolong. Inside the root, the path has every stop. On the page, the span stays, but the slot, the h3, and the shadow root are left out.
Real-life analogyTwo floor plans of one shop

Leaf and Kettle prints two floor plans. The staff's plan shows every room. The visitors' plan leaves the staff rooms blank. It still shows the front door, the tables, and the table where you sit.

In real life: The staff's floor plan
In JavaScript: composedPath() inside the closed root
In real life: The visitors' floor plan
In JavaScript: composedPath() on the page
In real life: Blank staff rooms
In JavaScript: The slot, the h3, and the shadow root
In real life: Your own table, still on the plan
In JavaScript: The slotted span

MDN puts it this way: the path doesn't include nodes in shadow trees whose root is closed. The DOM Standard adds one detail. A listener inside the closed root can reach those nodes, so its path keeps them all.

Why it matters: code inside a closed component handles its own clicks with the full path. Code on the page can't use composedPath() to look inside. Lesson 6.2 explains why closed still isn't a security wall.

Retargeting also changes event.relatedTarget, the second element some events carry, like focusout. Lesson 9.3, Focus and shadow DOM, covers it.

Why does event delegation miss clicks inside web components?

Event delegation means one listener high up handles clicks for many elements below it. Sites use it for click counting and add-to-cart buttons. The usual code is event.target.closest(".add"). closest() checks an element, then its parent, then the parent's parent, until one matches. Leaf and Kettle's page has its own Add Chai button, and a card with Add Oolong inside:

Delegation with closest() misses the card's buttonPop out in the code editor (opens in a new tab)HTML
<button class="add" data-tea="Chai">Add Chai</button><tea-card></tea-card> <script src="tea-card.js"></script><script>  document.addEventListener("click", (event) => {    const button = event.target.closest(".add");    console.log(button ? `Added ${button.dataset.tea}` : "No add button found");  });</script>
ResultLoading…
  • Line 1 is the page's own button. Line 2 is the card. In the tea-card.js tab, line 5 gives the card's button the same class, add.
  • Line 7 climbs from the target to the nearest .add.
  • Line 8 prints Added and the tea from data-tea, or No add button found.

Click Add Chai: Added Chai. Click Add Oolong: No add button found. On the page, the target is tea-card. closest() climbs from the card to the body, then to html. The button is below the card, in its shadow root. closest() never looks down.

Two ways to find the Add Oolong button from the page. Left: target.closest(".add") climbs tea-card, body, html and finds nothing. Right: composedPath() lists button.add, ShadowRoot, tea-card, body, html, ..., and its first stop is the button.target.closest(".add")tea-cardbodyhtmlfinds nothingcomposedPath()button.addShadowRoottea-cardbody, html, ...found
On the page, the target is tea-card. closest() climbs the page's tree from there and finds nothing. composedPath() starts at the button itself, so find() sees it first.

The fix is to search the path instead, because the path starts at the button:

Delegation with composedPath() finds both buttonsPop out in the code editor (opens in a new tab)HTML
<button class="add" data-tea="Chai">Add Chai</button><tea-card></tea-card> <script src="tea-card.js"></script><script>  document.addEventListener("click", (event) => {    const path = event.composedPath();    const button = path.find((node) => node.matches?.(".add"));    console.log(button ? `Added ${button.dataset.tea}` : "No add button found");  });</script>
ResultLoading…
  • Line 7 reads the path while the listener runs.
  • Line 8 finds the first stop that matches .add. matches() checks one element against a selector. A shadow root, the document, and the window have no matches(). So ?.() skips the call for them and gives undefined.

Now both clicks work: Added Chai, then Added Oolong. Lit's docs name another common case: a router that catches clicks on links. It checks the path for an a element, so links inside components work too.

This fix has two limits:

  • It reads another component's insides, so it can break when that component changes. Lit's docs warn about this too.
  • A closed root cuts its nodes out of the page's path. Then the page can't find the button at all.

The sturdy fix is for the component to announce the action with its own event, as lesson 5.3 showed. For example, the card could send a tea-add event with the tea's name, and the page would listen for that. The next lesson, on composed events, goes further.

Common mix-ups

  • "Retargeting stops the event." No. The event still reaches every listener on its path. Only what they read as the target changes.
  • "The host's own listener sees the inner button." No. The host is outside its shadow root, so it reads itself. Listen on the shadow root to read the button.
  • "A slotted element is retargeted to the host." No. The page wrote it, so every listener reads it as it is.
  • "composedPath() still works later, in a setTimeout." No. It's an empty array once the event is over. Copy what you need while the listener runs.
  • "After the event, event.target points at the inner button." No. It's what the page read, the host. If the event never left the root, it's null.
  • "event.target.closest() finds buttons inside components." No. It climbs from the host through the page's tree. Search composedPath() instead.
  • "Use event.path to get the real target." No. It was Chrome-only, and Chrome 109 removed it. Use composedPath().

Read each row across: what you read, then what it gives inside the root, on the page, and once the event is over.

What each listener reads, and when
What you readInside the shadow rootOn the pageAfter the event is over
event.targetThe node that was clicked, like the button.The host, like tea-card. A slotted node stays itself.What the page's listeners read. It's null if the event never left the root.
event.composedPath()Every stop, from the clicked node to window.The same list for an open root. A closed root's nodes are left out.An empty array.
event.currentTargetThe node whose listener is running, like the shadow root.The node whose listener is running, like document.null.

Practice exercises

For each one, ask two questions. Which tree is the listener in? And which tree is the node in?

Exercise 1 · Warm-upA word inside the button

Click the bold word Oolong. What does the root's listener print?

<tea-card></tea-card> <script>  class TeaCard extends HTMLElement {    constructor() {      super();      this.attachShadow({ mode: "open" });      this.shadowRoot.innerHTML = "<button>Add <b>Oolong</b></button>";      this.shadowRoot.addEventListener("click", (event) => {        console.log("Root:", event.target.localName);      });    }  }  customElements.define("tea-card", TeaCard);  document.addEventListener("click", (event) => {    console.log("Document:", event.target.localName);  });</script>
ResultLoading…

Answer, then press Check. Spacing and letter case don’t matter.

    Exercise 2 · Warm-upA slotted button

    The card is the one from the slots section. Click Oolong. What does the document's listener print?

    <tea-card>  <button slot="name">Oolong</button></tea-card> <script src="tea-card.js"></script><script>  document.addEventListener("click", (event) => {    console.log("Document:", event.target.localName);  });</script>
    ResultLoading…

    Answer, then press Check. Spacing and letter case don’t matter.

      Exercise 3 · PracticeRead the path in time

      Click Add Oolong. The console says Clicked: nothing. Fix it so it names the button. What does the fixed page print?

      <tea-card></tea-card> <script src="tea-card.js"></script><script>  document.addEventListener("click", (event) => {    setTimeout(() => {      const first = event.composedPath()[0];      console.log("Clicked:", first?.localName ?? "nothing");    }, 100);  });</script>
      ResultLoading…

      Answer, then press Check. Spacing and letter case don’t matter.

        Exercise 4 · PracticeWhich card was clicked?

        Click Oolong in the panel. The page says Not in a card, but Oolong shows inside the panel's card. Fix line 9. What does the fixed page print?

        <tea-panel>  <span slot="heading">Oolong</span></tea-panel> <script type="module">  import "./tea-kit/index.js";   document.addEventListener("click", (event) => {    const card = event.target.closest("tea-card");    console.log(card ? "Inside a card" : "Not in a card");  });</script>
        ResultLoading…

        Answer, then press Check. Spacing and letter case don’t matter.

          Exercise 5 · ChallengeWrite retarget() yourself

          Write retarget(a, b) from the rule. The page checks it against the browser's own event.target in three trees. Click Tasting notes. How many lines say PASS?

          <tea-panel>  <p>Floral</p></tea-panel> <script type="module">  import "./tea-kit/index.js";   function retarget(a, b) {    // Your code: follow the rule, and walk A up to a host when B can't see it.    return a;  }   const panel = document.querySelector("tea-panel");  const card = panel.shadowRoot.querySelector("tea-card");  for (const node of [card.shadowRoot, panel.shadowRoot, document]) {    node.addEventListener("click", (event) => {      const ok = retarget(event.composedPath()[0], event.currentTarget) === event.target;      console.log(ok ? "PASS" : "FAIL", event.target.localName);    });  }</script>
          ResultLoading…

          Answer, then press Check. Spacing and letter case don’t matter.

            Exercise 6 · ChallengeA card on a closed shelf

            An open card sits inside a closed shelf. Click Add Oolong. What does the console print?

            <tea-shelf></tea-shelf> <script>  class TeaCard extends HTMLElement {    constructor() {      super();      this.attachShadow({ mode: "open" }).innerHTML = "<button>Add Oolong</button>";    }  }  class TeaShelf extends HTMLElement {    constructor() {      super();      this.attachShadow({ mode: "closed" }).innerHTML = "<tea-card></tea-card>";    }  }  customElements.define("tea-card", TeaCard);  customElements.define("tea-shelf", TeaShelf);  document.addEventListener("click", (event) => {    console.log(event.composedPath()[0].localName);  });</script>
            ResultLoading…

            Answer, then press Check. Spacing and letter case don’t matter.

              Check your understanding

              For each question, find the listener's tree first. Then ask what it's allowed to see.

              The event retargeting quiz · 8 questionsScore: first tries count
              1. Question 1 of 8In the first example, what does the window's listener print after a click on Add Oolong?

                Read the code, then predictHTML
                <tea-card></tea-card>
                
                <script src="tea-card.js"></script>
                <script>
                  const card = document.querySelector("tea-card");
                  card.addEventListener("click", (event) => {
                    console.log("Card:", event.target.localName);
                  });
                  document.addEventListener("click", (event) => {
                    console.log("Document:", event.target.localName);
                  });
                  window.addEventListener("click", (event) => {
                    console.log("Window:", event.target.localName);
                  });
                </script>

                Choose an answer to see the explanation.

              2. Question 2 of 8A listener sits on tea-card itself, the host. A button inside its shadow root is clicked. What does the listener read as event.target?

                Choose an answer to see the explanation.

              3. Question 3 of 8In the kit's tea-panel page, a listener in the panel's shadow root hears a click on Tasting notes, the h4 in the card's root. What does it read?

                Choose an answer to see the explanation.

              4. Question 4 of 8A page writes <span slot="name">Oolong</span> inside a tea-card, and the reader clicks Oolong. What does a listener on document read?

                Choose an answer to see the explanation.

              5. Question 5 of 8What does line 8 of the setTimeout example print?

                Read the code, then predictHTML
                <tea-card></tea-card>
                
                <script src="tea-card.js"></script>
                <script>
                  document.addEventListener("click", (event) => {
                    console.log("During:", event.composedPath().length, event.target.localName);
                    setTimeout(() => {
                      console.log("After:", event.composedPath().length, event.target.localName);
                    });
                  });
                </script>

                Choose an answer to see the explanation.

              6. Question 6 of 8A card's shadow root is closed. The reader clicks Oolong, a span slotted into it. Where does the page's composedPath() start?

                Choose an answer to see the explanation.

              7. Question 7 of 8Why does event.target.closest(".add") on the page miss the Add Oolong button inside the card?

                Choose an answer to see the explanation.

              8. Question 8 of 8An event without composed: true is dispatched on a button inside a shadow root. After dispatchEvent() returns, what is its target?

                Choose an answer to see the explanation.

              Key takeaways

              • Each listener gets its own event.target. Inside a shadow root, it's the element clicked. Outside, it's the host.
              • The host's own listener reads the host, at phase 2. Capturing listeners read the host too.
              • With components inside components, each listener reads the nearest node it can see. The DOM Standard's retarget rule climbs one host at a time.
              • A slotted element belongs to the page, so every listener reads it as it is.
              • composedPath() lists every stop while the event runs, and is empty afterwards. composedPath()[0] is where the event started.
              • Once the event is over, target is what the page read, or null if the event never left the root.
              • A closed root cuts its nodes out of the page's path, even from the middle of it.
              • Page-wide delegation with closest() misses buttons inside components. Search composedPath(), or have the component send its own event.

              Remember the one-liner.
              Retargeting gives each listener the nearest node it may see, and composedPath() shows the whole route while the event runs.

              Sources

              The facts on this page come from these standards, docs, and source files:

              Coming next: Composed events. Which events cross a shadow root, and how to decide for your own.

              CompleteFrontend Clear concepts. Working examples.