Composition may be the killer feature of the Shadow DOM. By “composition” we mean composing an element’s light DOM children within its encapsulated shadow tree using <slot> elements.
This reduces the boilerplate required by those using a custom element and it helps reduce its API which makes it more maintainable since the entire DOM tree isn’t public by default.
I’ve written about <slot> elements before focusing how the Web platform’s slotting works differently from other forms of slotting and pointing out that the <slot> element itself can be styled despite its user agent styles (i.e. display: contents). In this post, I’m going to talk about slot assignment and explore a lesser known feature of it.
The default named slot assignment
The default named slot assignment behaviour of a shadow tree is to assign an element’s child nodes (i.e. elements and text nodes) to a corresponding <slot> element.
Text nodes and element nodes without a slot attribute are assigned to the first unnamed slot.
<div>
<!-- Declarative shadow DOM for visualization purposes only. Often this is set inside of the custom element definition. -->
<template shadowrootmode=open>
<slot></slot>
</template>
<span>I appear within the unnamed slot</span>
I also appear within the unnamed slot.
</div>
Element nodes with a slot attribute are assigned to the corresponding named slots (i.e. <slot> elements with a name attribute).
<my-article>
<!-- Declarative shadow DOM for visualization purposes only. Often this is set inside of the custom element definition. -->
<template shadowrootmode=open>
<hgroup>
<slot name=title></slot>
<slot name=subtitle></slot>
</hgroup>
<div class=article-content>
<slot></slot>
</div>
</template>
<h1 slot=title>Article title appears within the title slot</h1>
<p slot=subtitle>Article subtitle appears within the subtitle slot</p>
<p>Article content appears in the unnamed slot.</p>
I also appear within the unnamed slot.
</my-article>
Nodes that do not have a corresponding slot whether named or unnamed are ignored.
<div>
<!-- Declarative shadow DOM for visualization purposes only. Often this is set inside of the custom element definition. -->
<template shadowrootmode=open>
<slot name=content></slot>
</template>
<span slot=content>I appear within the named slot</span>
I don’t appear anywhere.
</div>
As you can see, slots are very powerful. They enable composition. They allow for mixed-order rendering which is incredibly useful for HTML streaming (e.g. for an app use case you could send the “app shell” in the first chunk and then chunk over content as it becomes available).
Named slot assignment works well for many simple use cases.
What if you want to wrap each individual slotted node with an element within the shadow tree? What if you only want to accept certain types of nodes or elements? You might think this is impossible or maybe even a design flaw of the Shadow DOM, but it does provide a method to do this.
Enter manual slot assignment
Manual slot assignment allows you to decide how an element’s child nodes get slotted.
You enable this when first attaching the shadow tree:
element.attachShadow({
mode: "open",
slotAssignment: "manual",
});
Once enabled, child nodes will not be auto-assigned to any <slot> element inside of the the shadow tree. That responsibility is all yours.
Assigning to slots
Nodes are assigned to slot elements using the assign() method of the HTMLSlotElement interface. Only nodes that are direct children of a shadow host, can be assigned to slots within its shadow tree.
The assign() method takes an ordered list of nodes and will unassign any node previously assigned to the slot when called.
// 0. Attach the open shadow root with manual slot assignment enabled
element.attachShadow({ mode: "open", slotAssignment: "manual" });
// 1. Create a slot element and append it to the shadow root.
const slot = document.createElement("slot");
element.shadowRoot.append(slot);
// 2. Find slottable nodes — must be either text or element nodes.
const slottables = Array.from(element.childNodes).filter(
node => node.nodeType === Node.ELEMENT_NODE || node.nodeType === Node.TEXT_NODE
);
// 3. Assign the slottable nodes to the slot.
slot.assign(...slottables);
That’s the gist of how to assign nodes to a slot manually.
Accessing slotted nodes
There are two methods to accessing what’s assigned to a slot:
- The
assignedNodes()method which includes all assignable nodes (i.e. text and element nodes). - The
assignedElements()method which only includes the element nodes.
Both of these methods also take an optional object of options with flatten as the only option currently available. This option defaults to false, but when set to true it will return the slot element’s children (i.e. the fallback content of the slot) if there is nothing assigned to it.
slot.assignedNodes({ flatten: true });
Practical use case: wrapping slotted elements
Say you have an element called <fruit-bowl>. This takes a list of fruit as direct child elements.
<fruit-bowl>
<span>Apple</span>
<span>Cherry</span>
<span>Apricot</span>
<span>Banana</span>
</fruit-bowl>
In the shadow tree, we have an <ul> element:
<!-- shadow tree content -->
<ul></ul>
Within that, each slotted fruit should be wrapped with an <li> element:
<li><slot></slot></li>
The resulting “composed tree” should look like this:
<!-- This is a composed tree: it does not represent the real DOM structure -->
<fruit-bowl>
<ul>
<li><slot><span>Apple</span></slot></li>
<li><slot><span>Cherry</span></slot></li>
<li><slot><span>Apricot</span></slot></li>
<li><slot><span>Banana</span></slot></li>
</ul>
</fruit-bowl>
When using manual slot assignment, MutationObservers are generally what you use to watch for changes of what’s slottable.
Generally, you’ll at least want a mutation observer that’s observing the shadow host’s light DOM children. In some cases, you might want an observer for the shadow tree as well.
It’s also important to be aware of at what point in the lifecycle of the document that the mutation observer has started. If it’s guaranteed that the observer has started early enough either as soon as the element is created or before its contents can be parsed, then there will be no need to check for existing slottable nodes. In other cases, it is necessary to check for existing slottable nodes when the element is connected (i.e. in custom elements check in the connectedCallback()).
To keep things simple, let’s assume the <fruit-bowl>’s custom element registration took place in a parser blocking way within the document’s <head>, so we don’t need to deal with any existing children. We’ll also only assume that the mutation observer is handling one entry at a time.
const slottableObserver = new MutationObserver((entries) => {
const { childNodes, shadowRoot } = entries[0].target;
// Reset the shadow root with an unordered list element.
shadowRoot.innerHTML = "<ul>";
const list = shadowRoot.querySelector("ul");
for (const node of childNodes) {
// Filter out non-elements
if (node.nodeType !== Node.ELEMENT_NODE) continue;
// Stub out the list item.
const listItem = document.createElement("li");
// Create and append a slot element within the list item.
const slot = document.createElement("slot");
listItem.append(slot);
// Append to the connected list, so we can assign to it.
list.append(listItem);
// Assign the corresponding light DOM child element.
slot.assign(node);
}
});
customElements.define("fruit-bowl", class extends HTMLElement {
constructor() {
super();
this.attachShadow({
mode: "open",
slotAssignment: "manual",
});
slottableObserver.observe(this, { childList: true });
}
});
Now, whenever the element’s light DOM children change, our custom element will wrap any child elements within a list item within the shadow root — neat! Give it a try:
Obviously, this is incredibly unoptimized — and we’re not going to get into improving it — but it demonstrates the kind of composition that manual slot assignment allows.
Beyond simply wrapping nodes, manual slot assignment can be a great way to further reduce boilerplate in your custom element APIs, especially when dealing with sub-component relationships (e.g. consumers don’t need to explicitly assign elements with the slot attribute; optional wrapping elements can be omitted). You can implicitly assign elements to slots based on their DOM position or even use DOM position to provide different templates. You can filter out unsupported content.
Manual slot assignment is just another way that Web Components APIs and the Shadow DOM allow you to create custom elements that are like those already included in the platform.






