HTML Slots: Named Content and Distribution
Render host children through slots
A shadow root is a separate DOM tree attached to a host. The next lesson explores it in detail. Here attachShadow creates an open root and assigns a fixed markup string to innerHTML. A default slot renders eligible direct host children without a named slot. The children remain in the light DOM; the slot controls their rendered placement.
<div id="host"> <p>Study notes</p></div><script> const host = document.querySelector("#host"); const root = host.attachShadow({mode: "open"}); root.innerHTML = "<section><slot></slot></section>";</script>The paragraph is rendered through the default slot but remains a child of host.
Name slots and supply fallback
A host child with slot="title" is assigned to a slot with name="title". If no nodes are assigned to a slot, its own children serve as fallback. Even whitespace text can count as an assignment to the default slot, so fallback depends on assigned nodes rather than visible text.
<div id="host"> <h2 slot="title">HTML</h2></div><script> const root = document.querySelector("#host").attachShadow({mode: "open"}); root.innerHTML = ``;</script>HTML is the assigned title; No details is the body fallback.
Inspect distribution changes
assignedElements() returns assigned element nodes; assignedNodes() also includes text. slotchange signals changes in assignment, not every mutation inside an assigned child. The example updates the count when another item is appended. The callback runs asynchronously after assignment changes.
<div id="host"> <span>HTML</span></div><output id="count"></output><script> const host = document.querySelector("#host"); const root = host.attachShadow({mode: "open"}); root.innerHTML = "<slot></slot>"; const slot = root.querySelector("slot"); slot.addEventListener("slotchange", () => { document.querySelector("#count").value = slot.assignedElements().length; }); const item = document.createElement("span"); item.textContent = "CSS"; host.append(item);</script>The output becomes 2.
Common mistakes and practice
Slots do not move light DOM nodes into the shadow tree. Use static trusted strings in innerHTML in these examples; use DOM creation or safe text insertion for untrusted values.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
HTML Slots: Named Content and Distribution — Knowledge Check
Apply the components concepts taught in this lesson.
Where does an assigned child remain in the DOM?
Which attribute names a slot itself?
When is fallback content displayed?
Which method returns only assigned elements?
What does slotchange report?