Manual slot assignment
Learn manual slot assignment in web components: set slotAssignment to manual, pick what each slot shows with slot.assign(), and know its limits.
- 01Turn on manual modeCreate a shadow root with
slotAssignment: "manual", and know that its mode is fixed and that it ignoresslotattributes. - 02Fill slots with assign()Show, reorder, move, and clear a slot's nodes with
slot.assign(), and know that it firesslotchange. - 03Know where it helps, and its limitsUse it for tabs and select-like components, and handle what it can't do: nodes outside the host, and new children.
What is manual slot assignment?
Asha writes three tasting notes inside the Oolong card at Leaf and Kettle: Floral, Sweet, and Honey finish. She wants the card to show one note at a time, a note of the day. Tomorrow it should show another one.
With the named slots from lesson 8.1, each child picks its own slot. So Ravi would put a slot attribute on today's note. Every morning, he would move it to another note. That means changing the page's own markup each day. Can the card itself choose which child shows?
Yes, with manual slot assignment. Create the shadow root with slotAssignment: "manual". Then the browser ignores slot attributes, and each slot shows only the nodes your code passes to its assign() method.
Here is Asha's card, showing the second note:
<tea-card> <p>Floral</p> <p>Sweet</p> <p>Honey finish</p></tea-card> <script> class TeaCard extends HTMLElement { constructor() { super(); this.attachShadow({ mode: "open", slotAssignment: "manual" }); this.shadowRoot.innerHTML = `<h3>Oolong</h3><slot></slot>`; } connectedCallback() { const slot = this.shadowRoot.querySelector("slot"); slot.assign(this.children[1]); } } customElements.define("tea-card", TeaCard);</script>- Lines 2 to 4 are the three notes. None has a
slotattribute. - Line 11 attaches the shadow root, with a new option:
slotAssignment: "manual". - Line 12 puts a heading and one slot in the root.
- Line 16 calls
assign()on the slot. It passesthis.children[1], the card's second element child. Counting starts at 0, so that's Sweet.
The result shows Oolong, then Sweet. Floral and Honey finish are still inside the card. They're its children, in its light DOM, as lesson 8.2 showed. But no slot shows them, so the browser doesn't draw them. Press Edit & run and change [1] to [2]. Now the card shows Honey finish.
In a busy café, each plate leaves the kitchen with a table number on it. A runner reads the number and carries the plate there. At Leaf and Kettle's tasting evening, Ravi works another way. The plates carry no numbers. He picks up each one and sets it on the table he chooses. A plate he doesn't place stays on the kitchen counter.
- In real life: A table number written on the plate
- In JavaScript: A
slotattribute on a child - In real life: The runner who reads the number
- In JavaScript: Named slot assignment, the default
- In real life: Ravi setting each plate down himself
- In JavaScript:
slot.assign()in your component - In real life: A plate left on the kitchen counter
- In JavaScript: A child no slot was given: it isn't drawn
With slotAssignment: "manual", the component decides what each slot shows. A slot shows the host's children you pass to its assign(), in your order. The page's slot attributes are ignored, and a child no slot was given isn't drawn.
Why it matters: the page writes plain HTML, with no labels at all. The component can change what shows at any time, with one call.
First comes how to turn the mode on, and how assign() behaves. Then where it helps: tabs, and select-like components. Then its limits. At the end, the kit gets a tea picker that places its own options.
How do you turn on manual slot assignment?
Manual slot assignment is a choice for a whole shadow root. You make it in the call that creates the root, attachShadow(). Its slotAssignment option takes one of two strings:
"named"is the default. Children go to slots by theirslotattribute, as in lesson 8.1."manual"means nothing goes to a slot by itself. Your code callsassign().
What happens to slot attributes a page already wrote? Here are the name and price spans from lesson 8.1, in a manual card:
<tea-card> <span slot="name">Oolong</span> <span slot="price">Price: 5</span></tea-card> <script> class TeaCard extends HTMLElement { constructor() { super(); this.attachShadow({ mode: "open", slotAssignment: "manual" }); this.shadowRoot.innerHTML = ` <h3><slot name="name">A new tea</slot></h3> <p><slot name="price">Ask at the counter</slot></p>`; } } customElements.define("tea-card", TeaCard); const card = document.querySelector("tea-card"); console.log(card.shadowRoot.slotAssignment); const nameSlot = card.shadowRoot.querySelector('slot[name="name"]'); console.log(nameSlot.assignedNodes().length);</script>- Lines 2 and 3 ask for the name slot and the price slot.
- Line 10 makes the root manual.
- Lines 12 and 13 are the two named slots, each with a fallback.
- Line 19 prints the root's mode:
manual. - Line 20 finds the name slot. A slot's
namestill works in a selector, like any attribute. - Line 21 prints how many nodes the name slot holds:
0.
The result shows A new tea and Ask at the counter. The spans asked for their slots, but nobody read the request. In a manual root, the DOM standard fills a slot only from the nodes passed to its assign(). The slot attribute stays on each span. It just does nothing.
Why it matters: a page can't fill a manual component the named way. If someone writes slot attributes for it, they're ignored. Say so in the component's docs.
Can you change the mode later?
No. The mode is set once, when the root is made. The slotAssignment property of a shadow root reads it. It has no setter, so you can read it but not change it.
<div id="box"></div> <script> const box = document.getElementById("box"); const root = box.attachShadow({ mode: "open" }); console.log(root.slotAssignment); root.slotAssignment = "manual"; console.log(root.slotAssignment); try { box.attachShadow({ mode: "open", slotAssignment: "manual" }); } catch (error) { console.log(error.name); }</script>- Line 5 attaches a root with no
slotAssignmentoption, so it's named. - Line 6 prints
named. - Line 7 tries to set the mode. Nothing happens. In strict code, like a class body or a module, this line throws a
TypeErrorinstead. - Line 8 prints
namedagain. - Line 10 tries to attach a second root, a manual one. It throws, and line 12 prints
NotSupportedError. An element gets one shadow root, as lesson 6.1 showed.
So one shadow root has one mode. You can't mix them, with some slots that match names and others filled by code. The proposal behind the feature kept the two apart on purpose. Mixing them would need complex rules, and its authors wrote that nobody wants to remember those.
When Leaf and Kettle opened, Asha painted a sign on the glass door: Please wait to be seated. The café across the road painted another one: Sit at the table on your ticket. Each café chose its rule on opening day. The paint doesn't come off, so the rule never changes.
- In real life: Painting the sign on opening day
- In JavaScript:
attachShadow({ slotAssignment }) - In real life: "Sit at the table on your ticket"
- In JavaScript:
"named": each child picks by itsslotattribute - In real life: "Please wait to be seated"
- In JavaScript:
"manual": the component picks withassign() - In real life: Reading the sign
- In JavaScript:
shadowRoot.slotAssignment
Why it matters: pick the mode when you design the component. If even one slot needs to be filled by code, the whole root goes manual, and your code fills every slot.
How does slot.assign() work?
slot.assign() tells one slot what to show. You pass it nodes, each as its own argument: slot.assign(floral, sweet). It takes elements and text nodes, the two kinds of slottable from lesson 8.1. The HTML standard calls the list it keeps the slot's manually assigned nodes.
Four rules decide what the slot shows:
- Each call replaces the slot's whole list. It never adds to it.
- The slot shows its nodes in the order you pass them.
- A node sits in one slot only. Assigning it to a second slot takes it out of the first.
- A call with nothing in the brackets empties the slot, so its fallback shows.
Try each rule. The card in the tea-card.js tab is manual, with a price slot and a notes slot. Each one has a fallback.
<tea-card> <span>Price: 5</span> <p>Floral</p> <p>Sweet</p></tea-card> <script src="tea-card.js"></script><script> const card = document.querySelector("tea-card"); const [price, notes] = card.shadowRoot.querySelectorAll("slot"); const [priceLine, floral, sweet] = card.children; notes.assign(floral); console.log("Price slot:", price.assignedNodes().length); console.log("Notes slot:", notes.assignedNodes().length);</script>Line 12 gives the notes slot one node. Sweet and the price line are still the card's children, but no slot shows them. So the price slot shows its fallback.
- In the
tea-card.jstab, line 4 makes the root manual. Lines 7 and 8 are the price slot and the notes slot. - In the page, lines 2 to 4 are the card's children: a price line and two notes. None has a
slotattribute. - Line 10 finds the two slots, in order. Line 11 names the three children.
card.childrenlists them in page order. - Line 12 is the line each choice changes. Lines 13 and 14 count each slot's nodes.
Now press each choice:
- One note shows Floral under Ask at the counter. The console prints
Price slot: 0andNotes slot: 1. - Two notes, your order shows Sweet above Floral. The page wrote them the other way round.
- The price shows Price: 5. The span needed no
slotattribute. - One node, two slots shows Floral in the price line, and No notes yet under it.
- Clear the slot shows No notes yet again.
In lesson 8.3, the host kept a list of guests for each table. For the tasting evening, Asha writes those lists herself. When she writes a table's list again, the old list goes in the bin. When she moves Ravi to table 2, she crosses him off table 1, because a guest sits at one table. A table with no names keeps its Reserved card.
- In real life: A table's list of guests
- In JavaScript: The nodes you pass to
slot.assign() - In real life: Writing a table's list again
- In JavaScript: Calling
assign()again: it replaces the whole list - In real life: Moving Ravi to table 2
- In JavaScript: Assigning a node to a second slot: it leaves the first
- In real life: A table with no names, and its Reserved card
- In JavaScript:
slot.assign()with nothing: the fallback shows
One more rule: you can't pass an array. slot.assign([floral, sweet]) throws a TypeError. To pass a list, spread it into separate arguments: slot.assign(...nodes). The spread and rest lesson covers the three dots. A comment, null, or undefined throws the same error.
Why it matters: think of assign() as writing a slot's whole list each time. To add one note, pass the old ones too.
Does slot.assign() fire slotchange?
Yes, when it changes a slot's list. Lesson 8.4 promised this. Here, a click moves Floral from one slot to the other:
<tea-card> <p>Floral</p></tea-card><button>Move Floral to the price line</button> <script src="tea-card.js"></script><script> const card = document.querySelector("tea-card"); const [price, notes] = card.shadowRoot.querySelectorAll("slot"); card.shadowRoot.addEventListener("slotchange", (event) => { console.log("slotchange on the", event.target.name || "default", "slot"); }); const floral = card.querySelector("p"); notes.assign(floral); document.querySelector("button").addEventListener("click", () => { price.assign(floral); });</script>- Line 10 listens for
slotchangeon the shadow root. Line 11 prints which slot fired. A default slot's name is an empty string, so|| "default"prints default instead. - Line 14 gives Floral to the notes slot when the page loads.
- Line 16 gives Floral to the price slot when you click.
On load, the console prints slotchange on the default slot. Click the button, and it prints two lines: one for the price slot, which gained Floral, and one for the default slot, which lost it. Click again, and nothing prints. Floral is already in the price slot, so no list changed.
The rest of lesson 8.4 holds too. The event waits for your script to end, and it bubbles only inside the shadow root. Chrome's code shows the steps in HTMLSlotElement::Assign(). It takes each node out of its old slot, keeps the new list in order, and marks every changed slot to fire.
When should you use manual slot assignment?
Named slots suit most components. MDN calls them the most suitable method for most use cases. Manual assignment helps when the page shouldn't have to say where each child goes. Two kinds of component need that:
- components that show one child of many, like tabs, a slideshow, or a form in steps;
- components that sort children by what they are, like a select, or a details box.
Before assign(), people used a trick. A component listened for slotchange and wrote slot attributes onto the page's children itself. A 2020 Stack Overflow answer does exactly that. It works, but the component edits the page's own markup, and the page can change it back. Manual assignment leaves the children as the page wrote them.
Showing one panel at a time
Tabs show one panel of many. Here are three panels, and three buttons in the page that pick one:
<tea-tabs> <p>Green tea: grassy and fresh.</p> <p>Oolong: floral, with a honey finish.</p> <p>Chai: spiced, with ginger.</p></tea-tabs><button>Green tea</button><button>Oolong</button><button>Chai</button> <script> class TeaTabs extends HTMLElement { constructor() { super(); this.attachShadow({ mode: "open", slotAssignment: "manual" }); this.shadowRoot.innerHTML = `<slot>Pick a tea</slot>`; } show(index) { this.shadowRoot.querySelector("slot").assign(this.children[index]); } } customElements.define("tea-tabs", TeaTabs); const tabs = document.querySelector("tea-tabs"); document.querySelectorAll("button").forEach((button, index) => { button.addEventListener("click", () => tabs.show(index)); });</script>- Lines 2 to 4 are the three panels, plain paragraphs.
- Lines 6 to 8 are three buttons in the page.
- Line 15 gives the one slot a fallback: Pick a tea.
- Lines 17 to 19 add a method,
show(). It assigns the child at positionindex. - Lines 24 and 25 call
show()with each button's position: 0, 1, or 2.
At first, the result shows Pick a tea. Click Oolong, and the slot shows Oolong: floral, with a honey finish. Click Chai, and Chai's panel takes its place. Each call replaces the list, so only one panel shows.
The other two panels aren't hidden with CSS. No slot holds them, so they're not in the flat tree at all, and the browser draws nothing for them.
Leaf and Kettle keeps every tin of tea on its shelves. The stand on the counter holds one tin: today's choice. Each morning, Asha swaps it for another. The other tins stay on the shelves, ready for their turn.
- In real life: Every tin on the shelves
- In JavaScript: The component's children
- In real life: The stand on the counter
- In JavaScript: The slot
- In real life: Swapping the tin each morning
- In JavaScript:
slot.assign(panel) - In real life: The tins still on the shelves
- In JavaScript: Children no slot holds: still in the light DOM, not drawn
This switcher is small on purpose. Its buttons live in the page, and they don't say which panel is on. Lesson 10.1, Building a tabs component, starts full tabs: the tab buttons as the component's own children, and what screen readers need. Lesson 10.2 adds the keyboard.
How do details and select use it?
The browser builds some of its own elements this way. Lesson 1.1 opened the hidden shadow root of <details>. It has two slots: one for your <summary>, and one for the rest. But your <summary> has no slot attribute. So how does it find its slot?
The HTML standard says the first slot takes the first <summary> child. The second slot takes everything else. That rule picks by kind and by position. A slot attribute can't say "the first summary". So Chrome makes the shadow root of <details> in manual mode, and its code assigns the children by hand, in ManuallyAssignSlots().
Chrome builds <select> the same way. Its constructor makes a manual shadow root. A select's first child may be a <button>: the select button you press to open the list. Chrome's code puts that button in one slot, and every other child in the list of options.
The proposal that led to assign() named this gap. Slots couldn't explain how <details> works, and Blink, Chrome's engine, had special code for it. Now any component can do the same.
Why it matters: when a component treats children by what they are, like "the first button" or "every panel but one", use manual mode. The practical section builds a select-like picker this way.
What are the limits of manual slot assignment?
Manual assignment gives you control, and with it, more work. Three limits are worth knowing.
Why doesn't slot.assign() show my element?
Here the card tries to show a paragraph that sits outside it, in the page:
<tea-card> <p>Floral</p></tea-card><p id="special">Today's special: Chai</p> <script src="tea-card.js"></script><script> const card = document.querySelector("tea-card"); const notes = card.shadowRoot.querySelector("slot:not([name])"); const special = document.getElementById("special"); notes.assign(special); console.log(notes.assignedNodes().length); console.log(special.assignedSlot);</script>- Line 4 is a paragraph in the page, outside the card.
- Line 11 assigns it to the card's notes slot. There's no error.
- Line 12 prints
0: the slot's assigned nodes are an empty list. - Line 13 prints the paragraph's
assignedSlot, from lesson 8.3:null.
The card shows No notes yet. Today's special shows under the card, as an ordinary paragraph. assign() kept the paragraph on the slot's list. But when the browser fills a slot, the DOM standard keeps only the nodes whose parent is the host. And assign() never moves a node. Elements one level down don't count either, as lesson 8.1 showed.
assign() keeps any element or text node you pass it. The slot shows only the ones whose parent is the host. Today's special sits in the page, so it isn't drawn.The slot does remember the paragraph. Move it into the card, and it shows at once. Why it matters: to show a node, make it a child of the host first. If nothing shows, check its parentNode.
What happens to new children?
A manual card shows Floral. Now the page adds a note, and takes one out and puts it back:
<tea-card> <p>Floral</p></tea-card><button id="add">Add Sweet</button><button id="out">Take Floral out</button><button id="back">Put Floral back</button> <script src="tea-card.js"></script><script> const card = document.querySelector("tea-card"); const notes = card.shadowRoot.querySelector("slot:not([name])"); notes.addEventListener("slotchange", () => { console.log("slotchange:", notes.assignedNodes().length, "nodes"); }); const floral = card.querySelector("p"); notes.assign(floral); document.getElementById("add").addEventListener("click", () => { card.insertAdjacentHTML("beforeend", "<p>Sweet</p>"); }); document.getElementById("out").addEventListener("click", () => floral.remove()); document.getElementById("back").addEventListener("click", () => card.append(floral));</script>- Lines 12 to 14 print the slot's node count each time it fires
slotchange. - Line 16 assigns Floral when the page loads. The console prints
slotchange: 1 nodes. - Line 18 adds a new note, Sweet, when you press Add Sweet.
- Line 20 takes Floral out of the card. Line 21 puts it back.
Press Add Sweet. Nothing shows, and the console stays quiet. Sweet is a child of the card, but it's on no slot's list. No list changed, so no slot fires slotchange. In a named root, the default slot would take Sweet at once.
Now press Take Floral out. The fallback shows, and the console prints slotchange: 0 nodes. Press Put Floral back. Floral shows again, with slotchange: 1 nodes. The card's code didn't call assign() again. Removing a node doesn't clear its manual slot assignment, and MDN notes it too. Once Floral is back in the card, the slot shows it.
Asha's seating plan is written at six. A guest who arrives at seven isn't on it. She waits by the door until Ravi seats her. A guest who steps out for a phone call keeps her seat, and sits down again when she comes back. A name on the plan for someone who isn't in the room seats nobody.
- In real life: A guest who arrives after the plan is written
- In JavaScript: A new child: on no slot's list
- In real life: Waiting by the door until Ravi seats her
- In JavaScript: Not drawn until your code calls
assign() - In real life: A guest who steps out for a call, then comes back
- In JavaScript: A child removed, then added back: it keeps its slot
- In real life: A name on the plan for someone not in the room
- In JavaScript: A node outside the host: on the list, not drawn
The same goes for children the parser hasn't read yet. If the class is defined before the card, its connectedCallback() runs before the notes exist, as lesson 8.3 showed. Then this.children[1] is undefined, and assign(undefined) throws a TypeError.
Why it matters: a manual component has to watch its own children. slotchange can't tell you about a child that's on no list. Use a MutationObserver, as lesson 5.5 did. The practical section does this.
Can you write a manual shadow root in HTML?
Yes. Declarative shadow DOM writes a shadow root as a <template> in the HTML. Stage 9, Server rendering, teaches it. The shadowrootslotassignment attribute makes that root manual:
<tea-card> <template shadowrootmode="open" shadowrootslotassignment="manual"> <h3>Oolong</h3> <slot>No notes yet</slot> </template> <p>Floral</p></tea-card> <script> const card = document.querySelector("tea-card"); console.log(card.shadowRoot.slotAssignment); console.log(card.shadowRoot.querySelector("slot").assignedNodes().length);</script>- Line 2 is the template.
shadowrootmodeturns it into a shadow root, andshadowrootslotassignment="manual"makes that root manual. - Line 6 is a note, a child of the card.
- Line 11 prints the mode:
manual. Line 12 prints the slot's node count:0.
The result shows Oolong and No notes yet. The HTML made a manual root, but HTML can't call assign(). Until your script runs, every slot shows its fallback. That's the last limit: manual slots need JavaScript.
The attribute matters for one more reason. A root the HTML made keeps its mode. When the class runs later, attachShadow() hands back that same root. The DOM standard ignores its slotAssignment option then. So a manual component rendered on a server needs the attribute in its HTML. Chrome 151, Firefox 151, and Safari 27 added it, and MDN has a longer example.
Named or manual?
Read each row across: one question, and how each mode answers it.
| Question | Named, the default | Manual |
|---|---|---|
| Who picks a child's slot? | The child, with its slot attribute. | Your component, with slot.assign(). |
| What does the page write? | A slot attribute on each child that wants a named slot. | Plain children. Any slot attribute is ignored. |
| What does a slot show, and in what order? | Every child that asks for it, in page order. | The nodes you passed to assign(), in your order. |
| What happens to a new child? | It goes to its slot at once. | It isn't drawn until your code assigns it. |
| What about spaces between the tags? | They fill the default slot and hide its fallback. | They show only if you assign them. |
| Can it change while the page runs? | Yes, when a child's slot attribute changes. | Yes, each time you call assign(). |
| Does a slot fill without JavaScript? | Yes. A shadow root written in HTML fills its slots. | No. A manual root written in HTML shows only fallback until a script calls assign(). |
Adding a tea picker to the kit
Asha's last request is a tea picker for the order form. A guest sees the teas as buttons. The one they pick moves up, to a line that says Your tea. That's what a select does, and Chrome's own select puts its button in one slot and its options in another. The kit's new tea-picker does the same. Here is the start of tea-kit/tea-picker.js:
const template = document.createElement("template");
template.innerHTML = `
<style>
.chosen { margin: 0 0 8px; }
.list { display: flex; flex-wrap: wrap; gap: 8px; }
</style>
<p class="chosen">Your tea: <slot name="chosen">none yet</slot></p>
<div class="list"><slot name="list"></slot></div>`;- Line 7 is the chosen slot, inside the Your tea line. Its fallback is none yet.
- Line 8 is the list slot, in a row.
The slots have names, but only so the code can find them. The root is manual, so a page can't use slot="chosen". Here is the class:
#chosen = null;
#observer = new MutationObserver(() => this.#place());
constructor() {
super();
this.attachShadow({ mode: "open", slotAssignment: "manual" });
this.shadowRoot.append(template.content.cloneNode(true));
this.addEventListener("click", (event) => {
const option = [...this.children].find((child) => child.contains(event.target));
if (!option) return;
this.#chosen = option;
this.#place();
});
}
#place() {
const options = [...this.children];
if (!options.includes(this.#chosen)) this.#chosen = null;
const [chosenSlot, listSlot] = this.shadowRoot.querySelectorAll("slot");
chosenSlot.assign(...options.filter((option) => option === this.#chosen));
listSlot.assign(...options.filter((option) => option !== this.#chosen));
}
connectedCallback() {
this.#place();
this.#observer.observe(this, { childList: true });
}- Line 1 keeps the chosen option in a private field. It starts as
null: nothing picked yet. - Line 2 makes a
MutationObserverthat calls#place()when the picker's children change. - Line 6 makes the root manual.
- Lines 8 to 13 handle a click. Line 9 finds the child that holds the click.
contains()is true for the child itself and for anything inside it. A click on the picker's own text finds nothing, so line 10 stops. Lines 11 and 12 remember the option and place every option again. - Lines 16 to 22 are
#place(). Line 17 takes the element children, in page order. Line 18 forgets a chosen option the page has removed. - Line 20 gives the chosen slot the chosen option, or nothing. Line 21 gives the list slot every other option.
- Lines 24 to 26 place the options when the picker joins the page, then start the observer. Its
disconnectedCallback()stops it, as lesson 5.5's tea menu does.
Two lines do all the slotting: 20 and 21. And line 17 takes this.children, the element children only. So the spaces and line breaks between the buttons never reach a slot. The blank-card trap from lesson 8.1 can't happen here.
The file ends with a read-only value property: the chosen option's text, or an empty string. Now the picker on a page:
<tea-picker> <button>Green tea</button> <button>Oolong</button> <button>Chai</button></tea-picker><p> <button id="add">Add Assam</button> <button id="check">Which tea?</button></p> <script type="module"> import "./tea-kit/index.js"; const picker = document.querySelector("tea-picker"); document.getElementById("add").addEventListener("click", () => { picker.insertAdjacentHTML("beforeend", "<button>Assam</button>"); }); document.getElementById("check").addEventListener("click", () => { console.log(picker.value || "No tea yet"); });</script>- Lines 1 to 5 are the picker, with three buttons. No button has a
slotattribute. - Line 12 loads the kit.
- Line 16 adds a fourth button, Assam, when you click Add Assam.
- Line 19 prints the picker's
value, or No tea yet.
The result shows Your tea: none yet, and three teas in a row. Click Oolong. It moves up: Your tea: Oolong. The row now shows Green tea and Chai. Click Add Assam, and Assam joins the row, because the observer placed it. Click Which tea?, and the console prints Oolong.
#place() gives Oolong to the chosen slot and every other option to the list. The page's buttons never move.The options are real buttons, so the keyboard works too. Press Tab to reach Oolong, then Enter. Oolong moves up, and it keeps the focus. It never moved in the DOM: only its slot changed.
Common mix-ups
- "The slot attribute still works in manual mode." No. The browser ignores it. Only
assign()puts a node in a slot. - "One shadow root can mix named and manual slots." No. The mode is set once, for the whole root, when it's made.
- "assign() can show any node on the page." No. A slot shows only the host's own children. Any other node stays on the list, but isn't drawn.
- "A node can show in two slots." No. Assigning it to a second slot takes it out of the first.
- "assign() adds to what the slot already shows." No. Each call replaces the whole list.
assign()with nothing empties it. - "New children find a slot by themselves." No. A new child waits, and no
slotchangefires. Watch the children with aMutationObserver. - "You pass assign() an array." No. Pass each node as its own argument, or spread the array. Chrome 86 to 91 took an array, so very old demos break today.
- "Calling assign() in a named root throws an error." No. It doesn't throw, and the slot keeps the nodes its name gives it.
- "To pick a slot from JavaScript, write slot attributes onto the children." No. That old trick edits the page's markup. Manual mode leaves the children as they are.
Practice exercises
Answer first, then use the hints. Each result runs live, so you can check yourself.
What does the card's price line show?
<tea-card> <span slot="price">Price: 5</span></tea-card> <script src="tea-card.js"></script>Ask at the counter. The root is manual, so the span's slot="price" does nothing. Nothing calls assign(), so the price slot shows its fallback.
What does line 13 print?
<tea-card> <p>Floral</p> <p>Sweet</p></tea-card> <script src="tea-card.js"></script><script> const card = document.querySelector("tea-card"); const [price, notes] = card.shadowRoot.querySelectorAll("slot"); const [floral, sweet] = card.children; notes.assign(floral, sweet); price.assign(sweet); console.log(notes.assignedNodes().length);</script>1. Line 12 gives Sweet to the price slot, so the notes slot loses it. Only Floral is left on its list.
Replace line 15 so the card shows only its last note. What does it show under Oolong?
<tea-card> <p>Floral</p> <p>Sweet</p> <p>Honey finish</p></tea-card> <script> class TeaCard extends HTMLElement { constructor() { super(); this.attachShadow({ mode: "open", slotAssignment: "manual" }); this.shadowRoot.innerHTML = `<h3>Oolong</h3><slot></slot>`; } connectedCallback() { // Show only the last note. } } customElements.define("tea-card", TeaCard);</script><tea-card> <p>Floral</p> <p>Sweet</p> <p>Honey finish</p></tea-card> <script> class TeaCard extends HTMLElement { constructor() { super(); this.attachShadow({ mode: "open", slotAssignment: "manual" }); this.shadowRoot.innerHTML = `<h3>Oolong</h3><slot></slot>`; } connectedCallback() { this.shadowRoot.querySelector("slot").assign(this.lastElementChild); } } customElements.define("tea-card", TeaCard);</script>Honey finish. The slot's list holds only the last note, so Floral and Sweet aren't drawn.
The card should show all three notes, but it shows none. Which kind of error does the console show? Then fix it.
<tea-card> <p>Floral</p> <p>Sweet</p> <p>Honey finish</p></tea-card> <script> class TeaCard extends HTMLElement { constructor() { super(); this.attachShadow({ mode: "open", slotAssignment: "manual" }); this.shadowRoot.innerHTML = `<h3>Oolong</h3><slot></slot>`; } connectedCallback() { this.shadowRoot.querySelector("slot").assign([...this.children]); } } customElements.define("tea-card", TeaCard);</script><tea-card> <p>Floral</p> <p>Sweet</p> <p>Honey finish</p></tea-card> <script> class TeaCard extends HTMLElement { constructor() { super(); this.attachShadow({ mode: "open", slotAssignment: "manual" }); this.shadowRoot.innerHTML = `<h3>Oolong</h3><slot></slot>`; } connectedCallback() { this.shadowRoot.querySelector("slot").assign(...this.children); } } customElements.define("tea-card", TeaCard);</script>A TypeError. assign() takes nodes as separate arguments, not an array. With ...this.children, the card shows all three notes.
Click Add a note: Sweet doesn't show. Replace line 17 so new notes show too. With your fix, what does one click print?
<tea-card> <p>Floral</p></tea-card><button>Add a note</button> <script> class TeaCard extends HTMLElement { constructor() { super(); this.attachShadow({ mode: "open", slotAssignment: "manual" }); this.shadowRoot.innerHTML = `<h3>Oolong</h3><slot></slot>`; const slot = this.shadowRoot.querySelector("slot"); slot.addEventListener("slotchange", () => console.log("Notes:", slot.assignedNodes().length)); } connectedCallback() { this.shadowRoot.querySelector("slot").assign(...this.children); // Assign the notes again each time the card's children change. } } customElements.define("tea-card", TeaCard); document.querySelector("button").addEventListener("click", () => { document.querySelector("tea-card").insertAdjacentHTML("beforeend", "<p>Sweet</p>"); });</script><tea-card> <p>Floral</p></tea-card><button>Add a note</button> <script> class TeaCard extends HTMLElement { constructor() { super(); this.attachShadow({ mode: "open", slotAssignment: "manual" }); this.shadowRoot.innerHTML = `<h3>Oolong</h3><slot></slot>`; const slot = this.shadowRoot.querySelector("slot"); slot.addEventListener("slotchange", () => console.log("Notes:", slot.assignedNodes().length)); } connectedCallback() { const slot = this.shadowRoot.querySelector("slot"); slot.assign(...this.children); new MutationObserver(() => slot.assign(...this.children)).observe(this, { childList: true }); } } customElements.define("tea-card", TeaCard); document.querySelector("button").addEventListener("click", () => { document.querySelector("tea-card").insertAdjacentHTML("beforeend", "<p>Sweet</p>"); });</script>Notes: 2. The observer runs after the click adds Sweet, and assigns both notes again. The slot's list changed, so slotchange prints the new count.
Make tea-tabs show the panel its show attribute names, counting from 0. The observedAttributes lesson has what you need. What does the result show?
<tea-tabs show="2"> <p>Green tea: grassy and fresh.</p> <p>Oolong: floral, with a honey finish.</p> <p>Chai: spiced, with ginger.</p></tea-tabs> <script> class TeaTabs extends HTMLElement { constructor() { super(); this.attachShadow({ mode: "open", slotAssignment: "manual" }); this.shadowRoot.innerHTML = `<slot>Pick a tea</slot>`; } // Show the panel the show attribute names, counting from 0. } customElements.define("tea-tabs", TeaTabs);</script><tea-tabs show="2"> <p>Green tea: grassy and fresh.</p> <p>Oolong: floral, with a honey finish.</p> <p>Chai: spiced, with ginger.</p></tea-tabs> <script> class TeaTabs extends HTMLElement { static observedAttributes = ["show"]; constructor() { super(); this.attachShadow({ mode: "open", slotAssignment: "manual" }); this.shadowRoot.innerHTML = `<slot>Pick a tea</slot>`; } attributeChangedCallback(name, oldValue, newValue) { const slot = this.shadowRoot.querySelector("slot"); const panel = this.children[Number(newValue)]; if (panel) slot.assign(panel); else slot.assign(); } } customElements.define("tea-tabs", TeaTabs);</script>Chai: spiced, with ginger. show="2" names the third child, counting from 0. The callback runs when the class upgrades the element, and the children are already there.
Check your understanding
For each question, ask two things: which nodes are on the slot's list, and which of them are the host's children?
Question 1 of 8Which line makes a shadow root use manual slot assignment?
Choose an answer to see the explanation.
Question 2 of 8What does this page show?
Read the code, then predict<tea-card> <span slot="name">Oolong</span> <span slot="price">Price: 5</span> </tea-card> <script> class TeaCard extends HTMLElement { constructor() { super(); this.attachShadow({ mode: "open", slotAssignment: "manual" }); this.shadowRoot.innerHTML = ` <h3><slot name="name">A new tea</slot></h3> <p><slot name="price">Ask at the counter</slot></p>`; } } customElements.define("tea-card", TeaCard); const card = document.querySelector("tea-card"); console.log(card.shadowRoot.slotAssignment); const nameSlot = card.shadowRoot.querySelector('slot[name="name"]'); console.log(nameSlot.assignedNodes().length); </script>Choose an answer to see the explanation.
Question 3 of 8Floral is assigned to the notes slot. Then
price.assign(floral)runs. What does the notes slot show?Choose an answer to see the explanation.
Question 4 of 8What does
notes.assign(), with nothing in the brackets, do?Choose an answer to see the explanation.
Question 5 of 8The card's code calls
notes.assign(special), wherespecialis a paragraph outside the card. What happens?Choose an answer to see the explanation.
Question 6 of 8A manual card shows Floral. The page adds
<p>Sweet</p>to the card. What happens?Choose an answer to see the explanation.
Question 7 of 8Which built-in elements does Chrome build with manual slot assignment inside?
Choose an answer to see the explanation.
Question 8 of 8Floral is assigned, then removed from the card, then put back. What does the notes slot show?
Choose an answer to see the explanation.
Key takeaways
attachShadow({ mode: "open", slotAssignment: "manual" })makes a root manual. The mode is fixed, andshadowRoot.slotAssignmentreads it.- In manual mode,
slotattributes are ignored. A slot shows the nodes passed to itsassign(), in that order. - Each
assign()call replaces the slot's list. A node sits in one slot only, andassign()with nothing shows the fallback. assign()firesslotchangewhen it changes a slot's list.- It helps when the component decides: tabs that show one panel, and select-like components that sort children by kind, as Chrome's
<details>and<select>do. - Only the host's own children show. New children wait for your code, so watch them with a
MutationObserver. A child taken out and put back keeps its slot. - A manual root written in HTML needs
shadowrootslotassignment="manual", and still needs a script to fill its slots.
Remember the one-liner.
In manual mode, the component, not the page, decides what each slot shows: the host's own children you pass to assign(), in your order.
Sources
The facts on this page come from these standards, docs, and source files:
- HTMLSlotElement: assign() method, MDN.
- Element.attachShadow(): slotAssignment, MDN.
- ShadowRoot: slotAssignment property, MDN.
- Using templates and slots: Named and manual slot assignment, MDN.
- HTML Standard: the assign() method, WHATWG.
- DOM Standard: Manual slot assignment, WHATWG.
- DOM Standard: Find slottables, WHATWG.
- DOM Standard: Attach a shadow root, WHATWG.
- html_slot_element.cc, HTMLSlotElement::Assign(), at Chromium 158.0.8127.18, Chromium.
- Imperative Shadow DOM Distribution API, Yuzhe Han and Hayato Ito, WICG.
- Is it possible to programmatically slot elements in web components?, Stack Overflow.
- HTML Standard: The details and summary elements (rendering), WHATWG.
- html_details_element.cc, ManuallyAssignSlots(), at Chromium 158.0.8127.18, Chromium.
- html_select_element.cc, the HTMLSelectElement constructor, at Chromium 158.0.8127.18, Chromium.
- Customizable select elements, MDN.
- select_type.cc, MenuListSelectType::ManuallyAssignSlots(), at Chromium 158.0.8127.18, Chromium.
- <template>: Declarative shadow DOM with manual slot assignment, MDN.
- New in Chrome 151, Chrome for Developers.
- Safari 27 release notes, Apple.
Coming next: Event retargeting, the first lesson of module 9. See why code outside a component sees its events come from the host, not from the elements inside.