Shadow DOM
📅
Shadow DOM: The Key to Web Components
We have now reached the crucial point in creating a web component - the Shadow DOM. It is this technology that provides:
- 🛡️ Style Isolation — CSS inside the component does not affect the outer page
- 🔒 DOM Encapsulation — external code does not have direct access to the internal structure
- 🧩 Composition via Slots — the ability to insert external content
What You Will Learn in This Section
- You might be surprised, but your HTML page doesn't just have a DOM; it has a Light DOM and a Shadow DOM, and they coexist harmoniously.
- Shadow DOM can be both user-defined and built-in.
- You will learn to create shadow trees using both approaches - imperative and declarative.
- You will understand why there are different modes for creating a shadow tree - open and closed.
- You will learn to apply styles and handle events, and discover how the Light and Shadow DOM trees interact.
Section Table of Contents
Shadow DOM Basics
- Light DOM
- Built-in Shadow DOM
- DOM Harmony
Creating Shadow DOM
- User-defined Shadow DOM
- Imperative Approach
- Declarative Approach
- Open and Closed Modes
Shadow DOM Interaction
- Styles
- Slots
- Events
Quick Start
Imperative Approach (JavaScript)
class MyComponent extends HTMLElement {
constructor() {
super();
this.attachShadow({mode: 'open'});
this.shadowRoot.innerHTML = `
<style>p { color: blue; }</style>
<p>Hello, Shadow DOM!</p>
`;
}
}
Declarative Approach (HTML)
<my-component>
<template shadowrootmode="open">
<style>p { color: green; }</style>
<p>Hello, Declarative Shadow DOM!</p>
</template>
</my-component>
Why Is This Important?
- Eliminates CSS conflicts between components
- Ensures reusability of components
- Enables server-side rendering (declarative approach)
- A browser standard — requires no libraries