Event retargeting
Learn shadow DOM event retargeting: why event.target shows the host, what each listener sees, and how composedPath() finds the element clicked.
- 01Say what each listener readsTell what
event.targetis inside a shadow root, on its host, and on the page, even with components inside components. - 02Use the retarget ruleWalk the DOM Standard's rule by hand, and explain why a slotted element stays the target.
- 03Find 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:
<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>- In the
tea-card.jstab, line 5 puts a button in the card's shadow root. Lines 6 to 8 listen inside the root.localNameis 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 onwindow.
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.
button. Every listener outside it, even the one on tea-card itself, reads tea-card.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
buttoninside 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 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?
<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>- Lines 5 to 7 listen on
documentwith{ 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.jstab is the card from the first example. Its root printsRoot: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, andwindow.
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?
<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>- 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.
h4. One in the panel's root reads tea-card, the nearest host it can see. One on the page reads tea-panel.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
h4that 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:
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:
- 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. - Step 1 has three ways to stop. Any one of them is enough.
- If A isn't a node, there's nothing to hide. Stop.
- 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.
- 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.
- 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:
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- A is
h4. Its root is the card's shadow root. The card's shadow root is inside that root, so the answer ish4.
h4The listener is in the same tree as the h4. Line 5 stops the loop on the first pass.
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:
<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>- Line 2 is the page's span, sent to the card's
nameslot, as in lesson 8.1. - In the
tea-card.jstab, line 5 puts anh3with 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.
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.
<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>- 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].
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?
<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>- 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:
<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>- 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:
<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>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.
- 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.jstab, 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.
span stays, but the slot, the h3, and the shadow root are left out.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:
<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>- Line 1 is the page's own button. Line 2 is the card. In the
tea-card.jstab, line 5 gives the card's button the same class,add. - Line 7 climbs from the target to the nearest
.add. - Line 8 prints
Addedand the tea fromdata-tea, orNo 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.
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:
<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>- 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 nomatches(). So?.()skips the call for them and givesundefined.
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 you read | Inside the shadow root | On the page | After the event is over |
|---|---|---|---|
event.target | The 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.currentTarget | The 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?
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>Root: b. The click starts at the b, the innermost element under the pointer. The root is in the same tree, so it reads b. The document reads tea-card.
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>Document: button. The Oolong button is the page's own, shown in the card's name slot. It isn't retargeted. The card's Add button is different: a click on it prints Document: tea-card.
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><tea-card></tea-card> <script src="tea-card.js"></script><script> document.addEventListener("click", (event) => { const first = event.composedPath()[0]; setTimeout(() => { console.log("Clicked:", first?.localName ?? "nothing"); }, 100); });</script>Clicked: button. The path is empty once the event is over, and the timer runs after that. Line 6 now reads it while the listener runs, and the variable keeps the button.
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><tea-panel> <span slot="heading">Oolong</span></tea-panel> <script type="module"> import "./tea-kit/index.js"; document.addEventListener("click", (event) => { const card = event.composedPath().find((node) => node.localName === "tea-card"); console.log(card ? "Inside a card" : "Not in a card"); });</script>Inside a card. closest() climbs the page's tree, where the span's parent is tea-panel. The path follows the slots instead: the panel's slot, the card's slot, the h3, the card's root, and then tea-card.
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><tea-panel> <p>Floral</p></tea-panel> <script type="module"> import "./tea-kit/index.js"; function retarget(a, b) { while (true) { const root = a.getRootNode(); if (!(root instanceof ShadowRoot)) return a; for (let node = b; node instanceof Node; node = node.getRootNode().host) { if (node.getRootNode() === root) return a; } a = root.host; } } 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>Three. Line 10 finds A's root, and line 11 stops when it isn't a shadow root. Lines 12 to 14 climb from B, one host at a time, and stop if they meet A's root. Line 15 moves A up to its host. Click Floral too: all three lines pass even with the starter, because a slotted node never moves.
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>tea-shelf. The button, the card's root, and the card are all inside the shelf's closed root. So the page's path starts at the first node it can reach, the shelf. Its event.target is tea-shelf too.
Check your understanding
For each question, find the listener's tree first. Then ask what it's allowed to see.
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.
Question 2 of 8A listener sits on
tea-carditself, the host. A button inside its shadow root is clicked. What does the listener read asevent.target?Choose an answer to see the explanation.
Question 3 of 8In the kit's
tea-panelpage, a listener in the panel's shadow root hears a click on Tasting notes, theh4in the card's root. What does it read?Choose an answer to see the explanation.
Question 4 of 8A page writes
<span slot="name">Oolong</span>inside atea-card, and the reader clicks Oolong. What does a listener ondocumentread?Choose an answer to see the explanation.
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.
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.
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.
Question 8 of 8An event without
composed: trueis dispatched on a button inside a shadow root. AfterdispatchEvent()returns, what is itstarget?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,
targetis what the page read, ornullif 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. SearchcomposedPath(), 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:
- DOM Standard: Dispatching events, WHATWG.
- DOM Standard: Retarget, WHATWG.
- DOM Standard: The composedPath() method, WHATWG.
- Event: composedPath() method, MDN.
- Event: composed property, MDN.
- Working with events in shadow DOM: Understanding event retargeting, Lit.
- Shadow DOM v1: The shadow DOM event model, Eric Bidelman, web.dev.
- Shadow DOM and events, Ilya Kantor, javascript.info.
- composed: true considered harmful?, Westbrook Johnson, open-wc.
- nsContentUtils.cpp, nsContentUtils::Retarget(), at Firefox 159.0.1, Mozilla.
- event.cc, Event::composedPath(), at Chromium 158.0.8127.18, Chromium.
- Remove Event.path, Chrome Platform Status.
Coming next: Composed events. Which events cross a shadow root, and how to decide for your own.