Skip to main content

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.

15 minBy Priygop Editorial TeamUpdated 2026Peer Reviewed & Verified

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 -->

Diagram
Loading diagram…

Shadow DOM prevents component CSS styles from leaking into the global page

Hands-on Practice Tools for this Course

Test what you learn using these free in-browser developer utilities (no signup required).

All 40+ Tools

Topics in This Module

0/9 done