Lesson 4 of 9
Shadow DOM & Encapsulation
The Shadow DOM creates an isolated DOM tree inside an element - its CSS and JavaScript don't leak out, and external styles don't leak in. This is the foundation of Web Components. It enables truly reusable, encapsulated components without naming conflicts or style collisions.
Shadow DOM Concepts
Shadow DOM creates isolation:
const host = document.querySelector('.widget');
const shadow = host.attachShadow({ mode: 'open' });
shadow.innerHTML = `
<style>/* Styles only apply inside shadow */
p { color: blue; }
</style>
<p>This text is blue (isolated)</p>
`;
Key concepts:
• mode: 'open' - Shadow DOM accessible via element.shadowRoot
• mode: 'closed' - Shadow DOM hidden (used by browser internals)
• :host - CSS selector for the host element from inside shadow
• ::slotted() - Style slotted (user-provided) content
• Light DOM vs Shadow DOM - Light DOM is the regular DOM, Shadow DOM is the isolated tree
Slots let users inject content:
<my-card>
<span slot='title'>Card Title</span>
<p>Card content goes here</p>
</my-card>
Inside the shadow DOM template:
<slot name='title'></slot>
<slot></slot> <!-- Default slot for unnamed content -->
Shadow DOM prevents component CSS styles from leaking into the global page
Finished this lesson?