Shadow DOM Slot API Reference

<slot>, slotchange, assignedNodes and shadow-root options explained

Reference for the Shadow DOM slot API — the slot element, named vs default slots, the slotchange event, assignedNodes and assignedElements, ::slotted styling, and attachShadow mode and delegatesFocus options.

What is the difference between a named slot and the default slot?

A <slot> with no name is the default slot and receives any light-DOM child that has no slot attribute. A <slot name='x'> only receives children whose slot='x'. There can be at most one default slot; extra unnamed slots stay empty. Unmatched children are not rendered.

Slots project light-DOM children into a component’s shadow tree. This reference covers the <slot> element, named slots, the slotchange event, the assignedNodes/assignedElements APIs, ::slotted() styling and the attachShadow options.

How it works

A component places <slot> elements in its shadow root. The browser then assigns the host’s light-DOM children into those slots to form the flattened tree that is actually rendered:

<my-card>
  <h2 slot="title">Hello</h2>   <!-- → <slot name="title"> -->
  <p>Body text</p>              <!-- → default <slot> -->
</my-card>

Inside the shadow root:

<div class="head"><slot name="title"></slot></div>
<div class="body"><slot></slot></div>

Children with a matching slot="..." attribute go to the named slot; everything else goes to the single default (unnamed) slot. Unmatched children render nothing. A slot’s own contents act as fallback shown only when no nodes are assigned.

Reacting and styling

  • Listen for slotchange on a slot to know when its assigned nodes change. It fires for assignment changes, not for mutations inside an already-assigned node.
  • Read what is assigned with slot.assignedElements({ flatten: true }) (elements only) or assignedNodes() (includes text/comments).
  • Style top-level projected nodes from the shadow root with ::slotted(selector) — it cannot reach descendants of assigned nodes.
  • attachShadow({ mode }) controls whether element.shadowRoot is exposed (open) or null (closed); delegatesFocus: true forwards focus to the first focusable child.