Shadow DOM and Encapsulation
Isolate styles and markup in shadow roots.
What Is the Shadow DOM?
The Shadow DOM gives an element a private, encapsulated DOM tree. Markup and styles inside it are isolated from the rest of the page.
- Outside CSS does not leak in.
- Inside CSS does not leak out.
- The internal structure is hidden from normal DOM queries.
attachShadow
You create a shadow tree by calling this.attachShadow({ mode: 'open' }). It returns a shadow root that you populate like a normal node.
class FancyBox extends HTMLElement {
constructor() {
super();
this.attachShadow({ mode: 'open' });
}
}
customElements.define('fancy-box', FancyBox);All lessons in this course
- Defining Custom Elements
- Lifecycle Callbacks
- Shadow DOM and Encapsulation
- Templates and Slots