CodeBlanks Logo Icon CodeBlanks

Shadow DOM basics

JavaScript course · Advanced · Lesson 94/100

Encapsulate styles and DOM by attaching a shadow root to an element.

Shadow DOM

Shadow DOM isolates an element's internal structure from the outside DOM. Styles and ids inside do not leak out, so components stay reusable and clash-free. It is often used with custom elements.

To attach a shadow root, call element.attachShadow({ mode: 'open' }). The returned shadow root is a container where you can append content like any DOM node. mode: 'open' allows outside access; closed blocks it.

attachShadow and shadow root

The typical way to attach a shadow root:

const root = element.attachShadow({ mode: 'open' });
root.innerHTML = '<p>Hello</p>';

Here innerHTML builds the shadow tree. The content is reachable only through the shadow root; the outer page's querySelector cannot see it. In open mode you reach the root via element.shadowRoot; in closed mode that returns null.

Outside content with slots

A slot is how you place outside content into the shadow DOM. You write <slot></slot> in the shadow tree; when the element is used, the children between its tags fall into that slot. This lets a component blend its own structure with content the user supplies.

Named slots let you define several points: <slot name="title"></slot>. Outside children with slot="title" go to the right slot.

Exercise Attach a shadow root to the box

Attach a shadow root to the box element in open mode. Place the HTML <p>Hello</p> inside it. Use a root variable for the shadow root.

Show example solution
1. Create a shadow root with box.attachShadow({ mode: 'open' }).
2. Assign the returned root to a variable named root.
3. Place a p element into root.innerHTML.

Example solution:
const root = box.attachShadow({ mode: 'open' });
root.innerHTML = '<p>Hello</p>';

Test yourself

  1. What does Shadow DOM provide?

    • Faster network requests
    • Automatic database access
    • Style and id isolation
    • Third-party cookies
    Show answer

    Style and id isolation — Correct. Shadow DOM hides and isolates internal styles and ids from the outer page.

  2. Attach a shadow root in open mode

    const root = element.attachShadow({ mode:____});
    Show answer
    const root = element.attachShadow({ mode:'open'});
  3. Match Shadow DOM terms

    shadowRoot
    Root of the shadow tree
    attachShadow
    Attaches a shadow root
    open
    Allows outside access
    closed
    Blocks outside access

All lessons in Advanced