What Is Shadow DOM — Complete Guide
In this tutorial, you will learn about What Is Shadow Dom. We cover key concepts, practical examples, and best practices to help you master this topic.
Shadow DOM is a browser API that creates encapsulated DOM subtrees with style isolation, enabling self-contained Web Components with scoped styles.
What You'll Learn
- What Shadow DOM is and how it differs from the regular DOM
- The problem of CSS conflicts and how Shadow DOM solves it
- How Shadow DOM enables component Encapsulation
- The relationship between Shadow DOM and Web Components
Why It Matters
CSS conflicts are a major problem in web development. Stylesheets from different components, libraries, and frameworks clash. Shadow DOM provides a browser-native solution.
flowchart LR A[Web Page] --> B[Light DOM] A --> C[Shadow DOM 1] A --> D[Shadow DOM 2] B --> E[Global styles] C --> F[Scoped styles] D --> G[Scoped styles]
What Shadow DOM Is
Shadow DOM is a DOM subtree attached to an element but rendered separately from the main document. Styles inside the shadow tree do not affect the outside, and external styles do not affect the shadow tree.
const host = document.querySelector('#shadow-host');
const shadow = host.attachShadow({ mode: 'open' });
shadow.innerHTML = '<p>This is inside Shadow DOM</p>';
console.log('Shadow root:', shadow);
console.log('Host element:', host);
console.log('Shadow host:', shadow.host);
The CSS Scoping Problem
Without Shadow DOM, component styles leak. With Shadow DOM, they are isolated.
<!-- Without Shadow DOM: styles leak -->
<style>.title { color: blue; }</style>
<div class="title">Page Title</div>
<div class="widget"><div class="title">Widget Title</div></div>
<!-- Widget's .title accidentally styled blue -->
// With Shadow DOM: styles are scoped
class ScopedWidget extends HTMLElement {
constructor() {
super();
this.attachShadow({ mode: 'open' });
this.shadowRoot.innerHTML = '<style>.title { color: red; }</style><div class="title">Widget Title</div>';
}
}
customElements.define('scoped-widget', ScopedWidget);
// The widget's .title is red. The page's .title is blue. No conflict.
Common Mistakes
- Thinking Shadow DOM replaces the regular DOM — It supplements it.
- Expecting Shadow DOM to provide security — It provides encapsulation, not security.
- Using Shadow DOM on elements that do not support it.
Practice Questions
- What is the main purpose of Shadow DOM? Style and DOM encapsulation.
- Can Shadow DOM be used without Custom Elements? Yes. Attach it to any compatible element.
Mini Project
Create a page with two instances of the same widget, one with Shadow DOM and one without. Demonstrate style leaking vs isolation.
What's Next
Lesson 2: Shadow Root Modes
Built by the developers of DodaTech
Doda Browser, DodaZIP & Durga Antivirus Pro