Shadow DOM
What is Shadow DOM?
Section titled “What is Shadow DOM?”Shadow DOM is a browser API that lets you attach a private, scoped DOM tree to any HTML element. That private tree is called the shadow tree, and the element it is attached to is called the host element. The rest of the page — the normal document tree — is called the light DOM.
The shadow tree is completely separate from the light DOM. Styles written inside it cannot leak out to the page, and page styles cannot accidentally style elements inside it. This is what “encapsulation” means in the context of web components.
Key concepts
Section titled “Key concepts”| Term | Meaning |
|---|---|
| Host element | The element that owns the shadow root (e.g., <my-card>) |
| Shadow root | The root node of the shadow tree, returned by attachShadow() |
| Shadow tree | All the nodes inside the shadow root |
| Light DOM | The main document tree — everything outside the shadow root |
| Encapsulated styles | CSS declared inside the shadow root that is scoped to the shadow tree only |
Shadow DOM structure
Section titled “Shadow DOM structure”flowchart LR LD["Light DOM"] HE["Host Element"] SR["Shadow Root"] ST["Shadow Tree"] IS["Internal <style>"] LD --> HE HE --> SR SR --> ST SR --> IS
What this module covers
Section titled “What this module covers”| Lesson | Topic |
|---|---|
| 1 | Shadow DOM — overview and structure (this page) |
| 2 | Attaching a Shadow Root — attachShadow, shadowRoot.innerHTML |
| 3 | Style Encapsulation — shadow boundary, scoped CSS |
| 4 | Open vs Closed Mode — mode: 'open' vs mode: 'closed' |
| 5 | Host Element and Shadow Boundary — :host, :host(selector), event retargeting |
Runnable demo
Section titled “Runnable demo”The element below attaches a shadow root and renders a styled greeting entirely inside the shadow tree. The blue color comes from a <style> tag placed inside the shadow root — not from the page.