ComposedPath Finds The Real Event Target
Listeners outside a shadow root only see the host as event.target; composedPath() returns the real inner chain, truncated to the host for closed roots.
Code
// Shadow DOM retargeting: listeners outside the shadow root see the host as event.target
const host = document.createElement('user-card');
const shadow = host.attachShadow({ mode: 'open' });
const button = document.createElement('button');
button.textContent = 'Save';
shadow.append(button);
document.body.append(host);
host.addEventListener('click', (event) => {
// From outside, event.target is the host element
console.log('target:', event.target.tagName);
// composedPath() hands back the real inner chain
console.log('real target:', event.composedPath()[0].tagName);
console.log('path length:', event.composedPath().length);
});
button.click();
// mode:'closed' truncates the path for outsiders: the first node is the host itself
const closedHost = document.createElement('closed-card');
const closedShadow = closedHost.attachShadow({ mode: 'closed' });
const inner = document.createElement('button');
closedShadow.append(inner);
document.body.append(closedHost);
closedHost.addEventListener('click', (event) => {
console.log('closed first node:', event.composedPath()[0].tagName);
});
inner.click();What the demo retargets
A click on the button inside an open shadow root reaches a listener on the host with event.target reported as the host, because retargeting hides inner nodes from outside observers. composedPath()[0] returns the button itself, the real first node of the propagation path.
The second half attaches a closed shadow root: composedPath still answers, but the path is truncated at the boundary, so the printed first node is the closed-card host and inner elements never appear to outsiders.
Points to remember
- Retargeting applies to any listener outside the shadow tree.
- closed mode cannot be escaped: even composedPath respects the boundary.
Interactive Tools for This Topic
DOM Event Propagation VisualizerVisualize DOM event capturing, targeting, and bubbling phases in real time. Toggle stopPropagation and stopImmediatePropagation to see how events traverse the tree.Argon2id Hash InfoEstimate Argon2id password-hash latency and memory usage, and check your parameters against OWASP 2024 minimum and recommended settings.bcrypt Cost EstimatorEstimate bcrypt cost factor latency and brute-force resistance, and get a recommended cost for your target hash time and attacker throughput.Box Shadow GeneratorBuild CSS box-shadow values with offset, blur, spread, color, opacity, and inset controls, with a live preview of the result.
FAQ
- What does composedPath return for a closed shadow root?
- A path truncated at the host: the demo prints the closed-card host as the first node, with no inner elements exposed to the outside listener.
Report a problem with this exampleOpens a pre-filled issue on GitHub.