Shadow Host and Tree — Complete Guide
In this tutorial, you will learn about Shadow Host and Tree. We cover key concepts, practical examples, and best practices to help you master this topic.
The shadow host is the element the shadow root is attached to, and the shadow tree is the encapsulated DOM subtree inside that shadow root.
What You'll Learn
- The relationship between host, shadow root, and shadow tree
- How to access the host from inside the shadow
- How the shadow tree affects rendering
- How slotted content relates to the shadow tree
Why It Matters
Understanding the host-shadow relationship is fundamental to debugging and structuring Web Components.
flowchart TD A[Shadow Host] --> B[Shadow Root] B --> C[Shadow Tree] B --> D[Slots] C --> E[Encapsulated DOM] C --> F[Encapsulated Styles] D --> G[Projected Light DOM]
Host and Shadow Relationship
class HostDemo extends HTMLElement {
constructor() {
super();
const shadow = this.attachShadow({ mode: 'open' });
// Inside shadow, access the host
console.log('Shadow host:', shadow.host); // The custom element itself
console.log('Is same as this:', shadow.host === this); // true
shadow.innerHTML = `
<style>
:host { display: block; padding: 16px; border: 2px solid #3498db; }
:host(.active) { border-color: #2ecc71; }
p { margin: 0; }
</style>
<p>Host tag: <slot name="tag"></slot></p>
`;
}
}
customElements.define('host-demo', HostDemo);
Shadow Tree Composition
The shadow tree replaces the host element's children. Without slots, host children are hidden.
const host = document.getElementById('demo');
const shadow = host.attachShadow({ mode: 'open' });
// This replaces the host's visual content
shadow.innerHTML = '<p>Shadow content (host children hidden without slots)</p>';
// Host children are still in the DOM
console.log('Host children:', host.children.length); // > 0
console.log('Shadow tree:', shadow.children.length); // 1
// Without a slot, host children are not rendered
// Add <slot></slot> to the shadow tree to render them
Common Mistakes
- Confusing shadow host children with shadow tree children
- Expecting host children to render without a slot
- Using this.shadowRoot from outside the class when mode is closed
Practice Questions
- What does shadow.host return? The element the shadow root is attached to.
- What happens to host children without a slot? They exist in the DOM but are not rendered.
Mini Project
Create a component that displays information about its own host and shadow tree. Show the host tag name, attributes, and the number of shadow tree children.
What's Next
Lesson 5: Encapsulation in Shadow DOM
Built by the developers of DodaTech
Doda Browser, DodaZIP & Durga Antivirus Pro