HTML Shadow DOM: Encapsulation and Event Boundaries
Create an open shadow root
A shadow host owns a separate tree. attachShadow({mode: "open"}) returns its ShadowRoot and exposes it through host.shadowRoot. Normal document selectors do not traverse this tree. Query the root directly to access its internal nodes. Not all HTML elements can host a shadow root.
<div id="host"></div><script> const host = document.querySelector("#host"); const root = host.attachShadow({mode: "open"}); const note = document.createElement("p"); note.textContent = "Internal note"; root.append(note);</script>The note renders but document.querySelector cannot locate it.
Scope styles without assuming total isolation
Rules inside a shadow tree are scoped to that tree, and ordinary document selectors cannot select its internal elements. Inheritable properties and CSS custom properties can still cross via the host. The fixed CSS and markup in this example give the internal paragraph a different color from the external paragraph.
<style>p { color: red; }</style><p>Outside</p><div id="host"></div><script> const root = document.querySelector("#host").attachShadow({mode: "open"}); root.innerHTML = "<style>p { color: blue; }</style><p>Inside</p>";</script>Outside is red; inside is blue.
Closed roots and event boundaries
With mode: "closed", host.shadowRoot returns null; the root returned by attachShadow is still usable by its creator. Closed mode is an API encapsulation convention, not a security boundary. Events that are both bubbling and composed can cross the shadow boundary, with the target retargeted to the host for outside listeners.
<div id="host"></div><output id="result"></output><script> const host = document.querySelector("#host"); const root = host.attachShadow({mode: "closed"}); const button = document.createElement("button"); button.textContent = "Review"; root.append(button); host.addEventListener("review", event => { document.querySelector("#result").value = event.target.id; }); button.dispatchEvent(new Event("review", {bubbles: true, composed: true}));</script>The outside listener sees host as the event target.
Common mistakes and practice
Do not treat closed roots as protection for secrets. Use a stable public API and preserve native accessibility inside the component. Experiment with inherited color on the host.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
HTML Shadow DOM: Encapsulation and Event Boundaries — Knowledge Check
Apply the components concepts taught in this lesson.
How do you access an open root after creation?
Does document.querySelector enter a shadow root?
Can inherited CSS properties cross via the host?
Is a closed root a security boundary?
Which option allows a bubbling custom event to cross the shadow boundary?