← Lessons

quiz vs the machine

Silver1120

Frontend

The Shadow DOM and Web Components

Encapsulate markup and styles into reusable elements with isolated DOM trees.

5 min read · intro · beat Silver to climb

Building blocks

Web components are a browser native way to make reusable custom elements. Three technologies combine.

  • Custom elements: register a tag with the customElements registry, backed by a class that extends HTMLElement.
  • Shadow DOM: attach a private DOM subtree that is isolated from the main document.
  • Templates and slots: declare reusable markup and project external content into named holes.

Why the shadow DOM matters

The shadow DOM creates a boundary. Styles inside do not leak out, and global page styles do not bleed in. This encapsulation is the main reason to use it.

  • Queries from the main document cannot reach into the shadow tree.
  • A slot element lets the host page pass children that render inside the component.
  • The boundary can be open, allowing script access through shadowRoot, or closed, hiding it.

Web components ship encapsulated UI that works in any framework or none.

Key idea

The shadow DOM gives custom elements an isolated tree where styles and markup stay encapsulated, projecting outside content through slots.

Check yourself

Answer to earn rating on the learn ladder.

1. What is the main benefit of the shadow DOM?

2. What does a slot element do?