Shadow DOM — Explained with Examples
Shadow DOM provides encapsulated DOM subtrees with style isolation, enabling self-contained web components that do not leak styles or behavior.
Shadow DOM is a browser API that attaches a hidden DOM tree to an element. Styles defined inside the shadow tree do not leak out, and external styles do not affect the shadow tree. This encapsulation is key for Web Components. A shadow root is attached to a host element via attachShadow({ mode: 'open' }). The mode determines whether external JavaScript can access the shadow tree.
Think of Shadow DOM like a terrarium inside a room. The plants (shadow DOM content) and their environment (styles) are completely enclosed in glass. You can see them (with open mode), but the soil and moisture inside do not affect the room, and the room’s environment does not affect the terrarium.
Shadow DOM solves the CSS scoping problem that has plagued web development. No more BEM naming conventions or CSS-in-JS hacks just to prevent style conflicts.
<!-- Custom element with shadow DOM -->
<my-tooltip text="Hello">Hover me</my-tooltip>
<script>
class MyTooltip extends HTMLElement {
constructor() {
super();
this.attachShadow({ mode: 'open' });
}
connectedCallback() {
this.shadowRoot.innerHTML = `
<style>
.tooltip { /* Scoped to shadow DOM only */
display: none;
background: #333;
color: white;
padding: 4px 8px;
border-radius: 4px;
}
:host(:hover) .tooltip {
display: inline-block;
}
</style>
<slot></slot>
<span class="tooltip">${this.getAttribute('text')}</span>
`;
}
}
customElements.define('my-tooltip', MyTooltip);
</script>Shadow DOM events can be composed (cross shadow boundary) or not, controlled by the composed option on custom events.
Built by the developers of DodaTech
Doda Browser, DodaZIP & Durga Antivirus Pro