0Pricing
JavaScript Academy · Lesson

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

  1. Defining Custom Elements
  2. Lifecycle Callbacks
  3. Shadow DOM and Encapsulation
  4. Templates and Slots
← Back to JavaScript Academy