Hiprup

What is the Shadow DOM?

The Shadow DOM gives an element its own isolated DOM subtree, with styles and markup scoped so they don't leak in or out.

  • Encapsulation — internal styles and structure are hidden from the main page.

  • Foundation of Web Components — used to build reusable, self-contained custom elements.

In short: it's why a custom component's CSS won't clash with the rest of your page.

// Create a Web Component with Shadow DOM
class MyCard extends HTMLElement {
  constructor() {
    super();
    const shadow = this.attachShadow({ mode: 'open' });

    shadow.innerHTML = `
      <style>
        /* Styles are SCOPED — do not leak out */
        .card { border: 1px solid #ccc; padding: 16px; border-radius: 8px; }
        h2 { color: blue; } /* Does not affect h2 outside shadow DOM */
      </style>
      <div class="card">
        <h2><slot name="title">Default Title</slot></h2>
        <slot>Default content</slot>
      </div>
    `;
  }
}

customElements.define('my-card', MyCard);

// Usage
// <my-card>
//   <span slot="title">Custom Title</span>
//   <p>Custom content</p>
// </my-card>

attachShadow creates an encapsulated DOM. Styles inside <style> are scoped — .card and h2 styles only affect elements inside this shadow DOM. <slot> allows external content to be projected into the shadow DOM. mode: 'open' allows external JS access via element.shadowRoot.

Shadow DOM provides TRUE style encapsulation (not conventions like BEM). Know: attachShadow, scoped styles, and <slot> for content projection.

Used by: Web Components, browser native elements (input, video). mode 'open' vs 'closed' controls external access.

What is the Shadow DOM? | Hiprup