The slot API
Learn how to get slotted elements in web components with assignedNodes(), assignedElements(), and assignedSlot, plus the flatten option and nested slots.
- 01Read what landed in a slotUse
assignedNodes()andassignedElements(), and say why spaces and line breaks show up in one list but not the other. - 02Read what a slot showsAdd
{ flatten: true }to get a slot's fallback, and the content behind a slot passed in from another component. - 03Find a node's slotRead
assignedSloton elements and text nodes, and say why it can benull.
How do you get slotted elements in a web component?
Asha writes two tasting notes inside the Oolong card at Leaf and Kettle: Floral, and Sweet. The card shows both, under the price. Now Ravi wants the card's code to count them. In lesson 8.2, he learned that a slot's own children are only its fallback. So slot.children gives him nothing.
Yet the slot knows what it holds. It draws both notes. So how do you ask a slot what landed in it? And how do you ask a note which slot it landed in?
Ask the slot. slot.assignedNodes() returns every node assigned to it, and slot.assignedElements() returns only the elements. To go the other way, read a node's assignedSlot. It returns the slot the node landed in.
Here are both questions, on a card with one slotted price:
<tea-card> <span slot="price">Price: 4</span></tea-card> <script> class TeaCard extends HTMLElement { constructor() { super(); this.attachShadow({ mode: "open" }); this.shadowRoot.innerHTML = ` <h3>Oolong</h3> <p><slot name="price">Ask at the counter</slot></p>`; } } customElements.define("tea-card", TeaCard); const card = document.querySelector("tea-card"); const slot = card.shadowRoot.querySelector("slot"); console.log(slot.assignedElements()[0].textContent); const price = card.querySelector("span"); console.log(price.assignedSlot.name);</script>- Line 2 is the card's child: a span that asks for the
priceslot. - Line 12 puts the price slot in the shadow root, with the fallback Ask at the counter.
- Line 18 finds that slot. Line 19 asks it for its assigned elements, takes the first one, and prints its text:
Price: 4. - Line 20 finds the span. Line 21 asks the span for its slot, and prints the slot's name:
price.
The result shows Oolong and Price: 4. The slot handed you the span, and the span handed you the slot. Nothing moved. The span is still the card's child, as lesson 8.2 showed. The calls that answer these two questions make up the slot API.
assignedElements() gives you the span. Ask the span, and assignedSlot gives you the slot. The span stays the card's child the whole time.At Leaf and Kettle's tasting evening, each table has a name, like Window. The host keeps a list for each table: who sits there. Each guest holds a place card with the name of their table. To find who sits at Window, read the host's list. To find where Asha sits, look at her place card.
- In real life: A table, like Window
- In JavaScript: A slot, like
<slot name="price"> - In real life: The host's list for that table
- In JavaScript:
slot.assignedNodes()andslot.assignedElements() - In real life: A guest at the table
- In JavaScript: A node the slot took, like the price span
- In real life: The guest's place card
- In JavaScript:
node.assignedSlot
A slot can list the nodes assigned to it, and each of those nodes can name its slot. assignedNodes() lists every node, text included. assignedElements() lists only elements. assignedSlot goes the other way. Add { flatten: true } to see what a slot really shows.
The first two are methods of the slot element. An element's interface is the set of methods and properties it has, and a slot's is called HTMLSlotElement. The third, assignedSlot, is a property of every element and every text node. This lesson takes them one at a time. At the end, Ravi passes slots from one component into another.
What is the difference between assignedNodes() and assignedElements()?
First, two words. A node is any piece of the page's tree: an element, a run of text, or a comment. An element is one kind of node: a tag, like <p>. So the two methods differ in one way. assignedNodes() lists every node in the slot, text included. assignedElements() keeps only the elements.
Here are Asha's two notes, written the usual way, one per line:
<tea-card> <p>Floral</p> <p>Sweet</p></tea-card> <script> class TeaCard extends HTMLElement { constructor() { super(); this.attachShadow({ mode: "open" }); this.shadowRoot.innerHTML = ` <h3>Oolong</h3> <slot></slot>`; } } customElements.define("tea-card", TeaCard); const slot = document.querySelector("tea-card").shadowRoot.querySelector("slot"); console.log(slot.assignedNodes().length); console.log(slot.assignedElements().length); for (const node of slot.assignedNodes()) console.log(node.nodeName);</script>- Lines 2 and 3 are the notes: two paragraphs, each on its own line.
- Line 13 is the card's only slot: a default slot, with no name.
- Line 19 counts the slot's assigned nodes. It prints
5. - Line 20 counts its assigned elements. It prints
2. - Line 21 prints each node's
nodeName, the name of its kind:#text,P,#text,P, and#text. An element'snodeNameis its tag in capitals. A text node's is#text.
Five nodes, but only two notes. The other three are the line breaks and spaces between the tags. The browser keeps them as text nodes, as lesson 5.5 showed with childNodes. Text can only go to the default slot, as lesson 8.1 showed. So assignedNodes() lists them too, though they draw nothing. Node properties and contents covers nodeName.
assignedNodes() lists all five. assignedElements() drops the three text nodes and keeps the two paragraphs.A delivery box arrives at Leaf and Kettle. Inside are two tins of tea, with crumpled paper around them. If Ravi lists everything in the box, he writes five things: paper, tin, paper, tin, paper. If he lists only the tins, he writes two.
- In real life: The delivery box
- In JavaScript: The default slot
- In real life: The two tins
- In JavaScript: The two
<p>elements - In real life: The crumpled paper
- In JavaScript: The spaces and line breaks, as text nodes
- In real life: Listing everything in the box
- In JavaScript:
assignedNodes() - In real life: Listing only the tins
- In JavaScript:
assignedElements()
Why it matters: to count or read the page's elements, use assignedElements(). Use assignedNodes() when plain text counts too, like a name written straight between the tags.
assignedElements() came later than assignedNodes(). It arrived in Chrome 65, Firefox 66, and Safari 12.1. Every major browser has had both since January 2020.
Now write the notes four ways, and watch both lists:
<tea-card> <p>Floral</p> <p>Sweet</p></tea-card> <script> class TeaCard extends HTMLElement { constructor() { super(); this.attachShadow({ mode: "open" }); this.shadowRoot.innerHTML = ` <h3>Oolong</h3> <slot></slot>`; } } customElements.define("tea-card", TeaCard); const slot = document.querySelector("tea-card").shadowRoot.querySelector("slot"); console.log("Nodes:", slot.assignedNodes().length); console.log("Elements:", slot.assignedElements().length); for (const node of slot.assignedNodes()) console.log(node.nodeName);</script>The line breaks and spaces around each <p> are text nodes. assignedNodes() lists them: #text, P, #text, P, #text. assignedElements() keeps the two paragraphs.
- One note per line gives 5 nodes and 2 elements, as above.
- All on one line gives 2 and 2. With no spaces between the tags, there are no text nodes.
- Plain text gives 1 node and 0 elements. The text shows, but it isn't an element.
- A comment gives 0 and 0. Comments are never slotted.
Why does assignedNodes() return an empty array?
Sometimes both lists come back empty, even though the card shows its notes. The usual reason is timing. Run this page, then click the button:
<script> class TeaCard extends HTMLElement { constructor() { super(); this.attachShadow({ mode: "open" }); this.shadowRoot.innerHTML = `<slot></slot>`; const slot = this.shadowRoot.querySelector("slot"); console.log("In the constructor:", slot.assignedElements().length); } } customElements.define("tea-card", TeaCard);</script> <tea-card> <p>Floral</p></tea-card><button>Count the notes</button> <script> const slot = document.querySelector("tea-card").shadowRoot.querySelector("slot"); document.querySelector("button").addEventListener("click", () => { console.log("On click:", slot.assignedElements().length); });</script>- Lines 1 to 12 define the card first, before the browser reads the card itself.
- Line 8 runs in the constructor. It counts the slot's elements and prints
In the constructor: 0. - Lines 14 to 16 are the card, with one note.
- Line 22 counts again when you click. It prints
On click: 1.
Why 0? The browser's HTML parser reads the page from top to bottom. When it reaches line 14, tea-card is already defined. So it builds a real card right away and runs its constructor. The paragraph on line 15 isn't read yet. The card has no children, so its slot has nothing to list. Lesson 3.6 showed the same gap in connectedCallback(), and an early Web Components issue describes it too.
The tasting starts at seven. At five, Ravi reads the host's list for the window table. It's empty. The list isn't wrong: the guests just haven't arrived. At seven, the same list has four names.
- In real life: Reading the list at five
- In JavaScript: Reading the slot in the constructor
- In real life: Guests who haven't arrived yet
- In JavaScript: Children the parser hasn't read yet
- In real life: Reading it again at seven
- In JavaScript: Reading it after the card's end tag, or on a click
- In real life: A bell that rings when someone sits down
- In JavaScript: The
slotchangeevent, in lesson 8.4
When the class is defined after the card, as in most examples here, the card is upgraded later. Its children are already there, so even the constructor sees them. Lesson 4.1 covers upgrades. But a component can't choose how a page loads it. So it needs to hear when its slots change. The slotchange event does that. It's the topic of lesson 8.4, Reacting to slotted content.
The other common reason for an empty list: nothing is assigned, and the slot shows its fallback. That's next.
What does the flatten option do?
Both methods take one option, { flatten: true }. Without it, a slot tells you what the page gave it. With it, the slot tells you what it shows. One asks "What did the page send?" The other asks "What's on the screen?"
An empty slot shows the difference best. Chai is new on the menu, and nobody wrote its price yet:
<tea-card></tea-card> <script> class TeaCard extends HTMLElement { constructor() { super(); this.attachShadow({ mode: "open" }); this.shadowRoot.innerHTML = ` <h3>Chai</h3> <p><slot name="price">Ask at the counter</slot></p>`; } } customElements.define("tea-card", TeaCard); const slot = document.querySelector("tea-card").shadowRoot.querySelector("slot"); console.log(slot.assignedNodes().length); const shown = slot.assignedNodes({ flatten: true }); console.log(shown.length); console.log(shown[0].textContent);</script>- Line 1 is the card, with nothing inside.
- Line 10 is the price slot, with the fallback Ask at the counter.
- Line 16 prints
assignedNodes().length:0. - Line 17 asks again, with
{ flatten: true }. Line 18 prints1. - Line 19 prints that one node's text:
Ask at the counter.
The result shows Chai and Ask at the counter. Without flatten, the slot returns an empty array. Its fallback isn't assigned to it. The fallback is the slot's own child, as lesson 8.2 showed. With flatten: true, the slot returns its fallback, because that's what it shows.
assignedNodes() returns an empty array. With { flatten: true }, the slot returns what it shows: its fallback text.The HTML standard gives the whole rule in one sentence. With flatten: true, a slot returns its assigned nodes if it has any, and its own children if not. Then it does the same for any slot in that list, again and again, until no slots are left. That last part matters when one component passes a slot into another. The section on nested slots shows it.
assignedElements({ flatten: true }) follows the same rule, then keeps only elements. Chai's fallback is text, so it would return an empty array here. A fallback such as <em>Ask at the counter</em> would come back as one element. MDN describes both methods the same way: with flatten, and nothing assigned, you get the fallback.
Why it matters: with flatten: true, you read what the reader sees. Without it, you read only what the page sent. Pick the question you mean.
How do you find which slot a node is in?
Now the reverse question. Every element and every text node has an assignedSlot property. It returns the <slot> the node landed in. If no slot took the node, it returns null.
<tea-card> <span slot="price">Price: 4</span> <span slot="photo">A photo of the leaves</span> Floral and sweet</tea-card> <script> class TeaCard extends HTMLElement { constructor() { super(); this.attachShadow({ mode: "open" }); this.shadowRoot.innerHTML = ` <p><slot name="price"></slot></p> <slot></slot>`; } } customElements.define("tea-card", TeaCard); const card = document.querySelector("tea-card"); const [price, photo] = card.children; console.log(price.assignedSlot.outerHTML); console.log(photo.assignedSlot); console.log(card.lastChild.assignedSlot.outerHTML);</script>- Lines 2 and 3 are two spans. One asks for the
priceslot, and one for aphotoslot. - Line 4 is bare text, with no tag around it.
- Lines 13 and 14 are the card's slots: a price slot and a default slot. There's no photo slot.
- Line 20 takes the card's first two element children and names them
priceandphoto. That's array destructuring. - Line 21 prints the price span's slot, as HTML:
<slot name="price"></slot>. - Line 22 prints the photo span's slot:
null. No slot has that name. - Line 23 asks the card's last child node, the text, for its slot. It prints
<slot></slot>: the default slot.
The result shows Price: 4, then Floral and sweet. The photo isn't drawn, and its assignedSlot says why. Text nodes have assignedSlot too, so you can ask a line of bare text where it went. Comments don't have it. They're never slotted.
Why it matters: when content doesn't show, read its assignedSlot. If it's null, no slot took it. Then compare the names, letter by letter.
Why is assignedSlot null?
Line 22 showed one reason: no slot has the node's name. There's a second one. Lesson 6.2 showed that a closed shadow root hides itself: the host's shadowRoot is null. The slot is part of that hidden tree. So the DOM standard checks the root first. If the root isn't open, assignedSlot returns null.
<tea-card> <span slot="name">Oolong</span></tea-card> <script> class TeaCard extends HTMLElement { #root; constructor() { super(); this.#root = this.attachShadow({ mode: "closed" }); this.#root.innerHTML = `<h3><slot name="name"></slot></h3>`; } connectedCallback() { const slot = this.#root.querySelector("slot"); console.log("Inside the card:", slot.assignedElements().length); } } customElements.define("tea-card", TeaCard); const name = document.querySelector("span"); console.log("From the page:", name.assignedSlot);</script>- Line 11 attaches a closed shadow root. It keeps the root in
#root, a private field only the card's own code can read. - Line 12 puts a name slot in it.
- Line 20 upgrades the card, which is already on the page. So
connectedCallback()runs. Lines 16 and 17 ask the card's own slot, through#root, and printInside the card: 1. - Line 23 asks the span from the page. It prints
From the page: null.
The result shows Oolong. The span is slotted and drawn, but it can't name its slot. It's like a hotel desk that won't give a caller a guest's room number. The guest is still in the room.
The check doesn't care who asks. Even inside the card, the span's assignedSlot is null. So in a closed component, start from the slot, as line 16 does. assignedNodes() and assignedElements() have no such check. Only code that holds the closed root can reach its slots anyway.
How do nested slots work?
Components are often built from other components. Ravi wants a tea panel for today's special: a box with a label, and a tea card inside. The page gives the panel a heading. The panel passes it on to the card's name slot.
The card lives inside the panel's shadow root, out of the page's reach. So the panel does the passing. Inside the card, it writes one of its own slots, with a slot attribute. A slot can be slotted, like any element. Passing content on this way is called re-slotting, or forwarding.
<tea-panel> <span slot="heading">Oolong</span></tea-panel> <script src="tea-card.js"></script><script src="tea-panel.js"></script><script> const panel = document.querySelector("tea-panel"); const card = panel.shadowRoot.querySelector("tea-card"); const slot = card.shadowRoot.querySelector("slot"); console.log(slot.assignedElements()[0].outerHTML); console.log(slot.assignedElements({ flatten: true })[0].outerHTML);</script>- In the
tea-panel.jstab, line 8 is the key line:<slot name="heading" slot="name">. Itsnamemakes it the panel's heading slot, for the page. Itsslotattribute sends it on to the card's name slot. Its fallback is Tea of the day. - In the
tea-card.jstab, line 5 is the card's name slot, with its own fallback, A new tea. - Back in the page, line 2 gives the panel a heading: Oolong.
- Lines 8 to 10 walk in, two shadow roots deep: the panel, then its card, then the card's name slot.
- Line 11 prints the card slot's first assigned element:
<slot name="heading" slot="name">Tea of the day</slot>. That's the panel's slot, with its fallback inside. - Line 12 asks again with
{ flatten: true }. It prints<span slot="heading">Oolong</span>: the page's own span.
The result shows Today's special, then Oolong. Without flatten, the card's slot sees only what was assigned to it: the panel's <slot>. It can't see past it. With flatten: true, the browser swaps that slot for what it holds. The DOM standard spells out the steps:
- Take the nodes assigned to the slot.
- If there are none, take the slot's own children, its fallback, instead.
- Swap each node that is itself a slot in a shadow root for that slot's own list, made with these same steps.
- Keep every other node as it is.
Step 3 repeats for every layer. So a heading passed through three components still comes out as the page's span. Chrome follows the same steps in its slot element's code, in CollectFlattenedAssignedNodes().
<slot>. With { flatten: true }, it lists the span.Ravi moves to a new flat and asks the post office to forward his mail. A parcel arrives at his old address. It gets a forwarding label and travels on to the new one. Ask the new building what came for Ravi, without opening anything, and you hear: one item, forwarded from the old address. Follow the label, and you find the parcel itself.
- In real life: The parcel
- In JavaScript: The page's span, Oolong
- In real life: The old address
- In JavaScript: The panel's
<slot name="heading"> - In real life: The new address
- In JavaScript: The card's
<slot name="name"> - In real life: The forwarding label
- In JavaScript:
slot="name"on the panel's slot - In real life: Seeing only the forwarding label
- In JavaScript:
assignedElements(): the panel's slot - In real life: Following the label to the parcel
- In JavaScript:
assignedElements({ flatten: true }): the span
Now change what the page gives the panel, and read the card's slot three ways:
<tea-panel> <span slot="heading">Oolong</span></tea-panel> <script src="tea-card.js"></script><script src="tea-panel.js"></script><script> const panel = document.querySelector("tea-panel"); const card = panel.shadowRoot.querySelector("tea-card"); const slot = card.shadowRoot.querySelector("slot"); const names = (nodes) => nodes.map((node) => node.nodeName).join(" ") || "nothing"; console.log("Elements:", names(slot.assignedElements())); console.log("Elements, flattened:", names(slot.assignedElements({ flatten: true }))); console.log("Nodes, flattened:", names(slot.assignedNodes({ flatten: true })));</script>The card's name slot holds the panel's <slot>. flatten: true swaps that slot for what it holds: the page's span, Oolong.
- A heading gives
SLOTwithout flatten, andSPANwith it. The card shows Oolong. - Nothing shows Tea of the day, the panel slot's fallback. It's text, so only the flattened node list has it:
#text. - slot="name" asks for the card's slot name, but the panel has no slot by that name. The span isn't drawn.
Look at Nothing again. The card's own fallback, A new tea, never shows inside the panel. The card's slot always has the panel's slot assigned to it. So the card's fallback stays hidden, and the panel slot's fallback shows instead. Why it matters: give each forwarding slot its own fallback. And page authors must use the outer component's slot names, never the inner one's.
Following a node through two slots
assignedSlot follows the chain from the other end, one step at a time:
<tea-panel> <span slot="heading">Oolong</span></tea-panel> <script src="tea-card.js"></script><script src="tea-panel.js"></script><script> const heading = document.querySelector("span"); const first = heading.assignedSlot; console.log(first.name); console.log(first.assignedSlot.name);</script>- Line 8 finds the page's heading span.
- Line 9 asks it for its slot. That's the panel's slot, so line 10 prints
heading. - Line 11 asks the panel's slot for its own slot. That's the card's, so it prints
name.
Each assignedSlot goes one layer in. A slot is an element, so it has an assignedSlot too. Why it matters: when a forwarded heading doesn't show, follow it layer by layer. The step that gives null is where the chain breaks.
Adding a tea panel to the kit
Ravi's panel joins the tea shop kit as tea-kit/tea-panel.js. It wraps the kit's real card from lesson 8.1, which has three slots. So the panel forwards three: the heading, the price, and the default slot. Here are the file's first 16 lines:
import "./tea-card.js";
const template = document.createElement("template");
template.innerHTML = `
<style>
.panel { border: 2px dashed seagreen; border-radius: 8px; padding: 8px 12px; }
.label { margin: 0 0 8px; }
</style>
<div class="panel">
<p class="label">Today's special</p>
<tea-card>
<slot name="heading" slot="name">Tea of the day</slot>
<slot name="price" slot="price">Ask at the counter</slot>
<slot></slot>
</tea-card>
</div>`;- Line 1 imports the card's file, so the card is defined wherever the panel is.
- Lines 3 to 16 build one template for every panel, as the card does since lesson 7.1.
- Line 10 is the label, Today's special.
- Line 12 forwards the panel's
headingslot to the card'snameslot. - Line 13 forwards
pricetoprice. The two names can match, or differ, as on line 12. - Line 14 forwards the default slot. A
<slot>with noslotattribute goes to the card's default slot, like any other child.
The heading and price slots have their own fallback, for the reason the playground showed: the card's fallback can't show through. The rest of the file is the class, which clones the template into an open shadow root, and its define() call.
Now a page with three kinds of card. Ravi wants to print the name each one shows, wherever the name came from:
<tea-card name="Green tea" price="4"></tea-card><tea-card price="3"> <span slot="name">Black tea <small>(strong)</small></span></tea-card><tea-panel> <span slot="heading">Oolong</span> <span slot="price">Price: 5</span> Floral, with a honey finish.</tea-panel> <script type="module"> import "./tea-kit/index.js"; const panel = document.querySelector("tea-panel"); const inner = panel.shadowRoot.querySelector("tea-card"); for (const card of [...document.querySelectorAll("tea-card"), inner]) { const slot = card.shadowRoot.querySelector('slot[name="name"]'); const shown = slot.assignedNodes({ flatten: true }); console.log(shown.map((node) => node.textContent).join("")); }</script>- Line 1 is a card whose name comes from its
nameattribute. The kit writes it as the slot's fallback. - Line 3 slots a name with a note in it, straight into a card.
- Lines 5 to 9 are a panel. Line 6 gives it a heading, line 7 a price, and line 8 a tasting note.
- Line 12 loads the kit, now with the panel.
- Line 15 finds the card inside the panel.
document.querySelectorAll()can't find it, because queries stop at a shadow root, as lesson 6.3 showed. - Lines 16 to 20 go through all three cards. Line 18 takes each name slot's flattened nodes. Line 19 joins their text and prints it:
Green tea,Black tea (strong), andOolong.
One loop, three sources. For the first card, flatten: true returns the fallback text from the attribute. For the second, it returns the slotted span. For the third, it follows the panel's slot to the page's heading. Without flatten, the first card would print an empty line, and the third would print Tea of the day. Exercise 5 shows that last one.
Libraries wrap these calls for you. Lit, a library for web components that the Lit stage covers, has two decorators for them. A decorator is a line starting with @ that changes the class member under it. @queryAssignedElements turns a property into a getter. Given { slot: "name", flatten: true }, it calls assignedElements({ flatten: true }) on the name slot each time you read the property. @queryAssignedNodes does the same with assignedNodes(). Spot the slot API inside, and you know what they return.
Read each row across: what each call does with spaces, with an empty slot, and with a slot passed in.
| Which call | Does it list spaces and line breaks? | Does it list an empty slot's fallback? | What does it list for a slot passed in? |
|---|---|---|---|
assignedNodes() | Yes, as text nodes. | No. It returns an empty array. | It lists the other component's <slot> element. |
assignedElements() | No. It keeps only elements. | No. It returns an empty array. | It lists the other component's <slot> element. |
assignedNodes({ flatten: true }) | Yes, as text nodes. | Yes. It returns the slot's own children. | It lists what that slot holds instead. |
assignedElements({ flatten: true }) | No. It keeps only elements. | Only if the fallback has elements. | It lists the elements that slot holds instead. |
Now sort what each call lists. The card has a default slot, and a name slot with the panel's slot in it.
- A
<p>the page wrote between the card's tags - A line break between the card's tags
- A comment between the card's tags
- The fallback text of a slot with nothing assigned
- The fallback text of a slot that has assigned nodes
- The panel's
<slot>, assigned to the card's name slot - The page's span, passed in through the panel's slot
- A
<b>inside a slotted<p>
Sort each node by the calls that list it. assignedNodes() means no options.
Common mix-ups
- "assignedNodes() returns only elements." No. It returns text nodes too, even the spaces and line breaks between tags.
assignedElements()returns only elements. - "An empty slot's assignedNodes() returns its fallback." No. It returns an empty array. Only
{ flatten: true }returns the fallback. - "flatten: true lists the children of slotted elements." No. It only opens slots. A slotted
<p>comes back whole, with its<b>still inside. - "The constructor is a good place to read slots." No. When the class is defined before the page reads the card, the card's children aren't parsed yet.
- "If assignedSlot is null, the node isn't drawn." No. A node in a closed root's slot is drawn, and its
assignedSlotis stillnull. - "Inside a nested component, the inner slot lists the page's content." No. It lists the outer component's
<slot>, unless you add{ flatten: true }. - "The page can fill an inner component's slots." No. The inner component sits in a shadow root. The page can only use the outer component's slot names.
- "The slot API moves nodes into the slot." No. It only reads. The nodes stay the host's children.
Practice exercises
Answer first, then use the hints. Each result runs live, so you can check yourself.
What does line 18 print?
<script> class TeaCard extends HTMLElement { constructor() { super(); this.attachShadow({ mode: "open" }); this.shadowRoot.innerHTML = `<h3><slot></slot></h3>`; } } customElements.define("tea-card", TeaCard);</script> <tea-card> <b>Mint tea</b></tea-card> <script> const slot = document.querySelector("tea-card").shadowRoot.querySelector("slot"); console.log(slot.assignedNodes().length);</script>3. The line break before the <b> and the one after it are text nodes. With the <b>, the default slot gets three nodes.
Nothing is assigned to the price slot. What does line 16 print?
<script> class TeaCard extends HTMLElement { constructor() { super(); this.attachShadow({ mode: "open" }); this.shadowRoot.innerHTML = `<p><slot name="price"><em>Ask at the counter</em></slot></p>`; } } customElements.define("tea-card", TeaCard);</script> <tea-card></tea-card> <script> const slot = document.querySelector("tea-card").shadowRoot.querySelector("slot"); console.log(slot.assignedElements({ flatten: true }).length);</script>1. With nothing assigned, flatten: true returns the slot's own children: its fallback. The fallback is one <em> element, so assignedElements() keeps it.
Replace line 19 so the console prints the text of each note. What does it print first?
<script> class TeaCard extends HTMLElement { constructor() { super(); this.attachShadow({ mode: "open" }); this.shadowRoot.innerHTML = `<h3>Oolong</h3><slot></slot>`; } } customElements.define("tea-card", TeaCard);</script> <tea-card> <p>Floral</p> <p>Sweet</p></tea-card> <script> const slot = document.querySelector("tea-card").shadowRoot.querySelector("slot"); // Print the text of each note here.</script><script> class TeaCard extends HTMLElement { constructor() { super(); this.attachShadow({ mode: "open" }); this.shadowRoot.innerHTML = `<h3>Oolong</h3><slot></slot>`; } } customElements.define("tea-card", TeaCard);</script> <tea-card> <p>Floral</p> <p>Sweet</p></tea-card> <script> const slot = document.querySelector("tea-card").shadowRoot.querySelector("slot"); for (const note of slot.assignedElements()) { console.log(note.textContent); }</script>Floral, then Sweet. assignedElements() lists only the two paragraphs, so the loop prints one line per note, in page order.
Line 19 should count the notes, but it prints 0. Fix it. What does it print now?
<script> class TeaCard extends HTMLElement { constructor() { super(); this.attachShadow({ mode: "open" }); this.shadowRoot.innerHTML = `<h3>Oolong</h3><slot></slot>`; } } customElements.define("tea-card", TeaCard);</script> <tea-card> <p>Floral</p> <p>Sweet</p></tea-card> <script> const slot = document.querySelector("tea-card").shadowRoot.querySelector("slot"); console.log(slot.children.length);</script><script> class TeaCard extends HTMLElement { constructor() { super(); this.attachShadow({ mode: "open" }); this.shadowRoot.innerHTML = `<h3>Oolong</h3><slot></slot>`; } } customElements.define("tea-card", TeaCard);</script> <tea-card> <p>Floral</p> <p>Sweet</p></tea-card> <script> const slot = document.querySelector("tea-card").shadowRoot.querySelector("slot"); console.log(slot.assignedElements().length);</script>2. slot.children holds only the slot's fallback, and this slot has none. assignedElements() lists the two paragraphs the page wrote.
The panel shows Oolong. Predict first: what does line 10 print?
<tea-panel> <span slot="heading">Oolong</span></tea-panel> <script src="tea-card.js"></script><script src="tea-panel.js"></script><script> const card = document.querySelector("tea-panel").shadowRoot.querySelector("tea-card"); const slot = card.shadowRoot.querySelector("slot"); console.log(slot.assignedNodes()[0].textContent);</script>Tea of the day. The card's slot holds the panel's slot, not the span. That slot's textContent is its own fallback, even though Oolong is what shows. With { flatten: true } on line 10, it prints Oolong.
The card has two slots named price: one in a header, one in a footer. Replace line 21 with one line that prints the tag name of the element around the price's slot. What does it print?
<script> class TeaCard extends HTMLElement { constructor() { super(); this.attachShadow({ mode: "open" }); this.shadowRoot.innerHTML = ` <header><slot name="price">Ask at the counter</slot></header> <h3>Green tea</h3> <footer><slot name="price">Ask at the counter</slot></footer>`; } } customElements.define("tea-card", TeaCard);</script> <tea-card> <span slot="price">Price: 4</span></tea-card> <script> const price = document.querySelector("span"); // Print the tag name of the element around the price's slot.</script><script> class TeaCard extends HTMLElement { constructor() { super(); this.attachShadow({ mode: "open" }); this.shadowRoot.innerHTML = ` <header><slot name="price">Ask at the counter</slot></header> <h3>Green tea</h3> <footer><slot name="price">Ask at the counter</slot></footer>`; } } customElements.define("tea-card", TeaCard);</script> <tea-card> <span slot="price">Price: 4</span></tea-card> <script> const price = document.querySelector("span"); console.log(price.assignedSlot.parentElement.localName);</script>header. The price goes to the first slot named price in the shadow tree, the one in the header. Lesson 8.2 found it with DevTools' badge. assignedSlot finds it in code.
Check your understanding
For each question, ask two things: are you asking the slot or the node, and does it need flatten?
Question 1 of 7A card's two notes are written one per line between its tags. Which call returns only the two
<p>elements?Choose an answer to see the explanation.
Question 2 of 7What does line 19 of this page print?
Read the code, then predict<tea-card> <p>Floral</p> <p>Sweet</p> </tea-card> <script> class TeaCard extends HTMLElement { constructor() { super(); this.attachShadow({ mode: "open" }); this.shadowRoot.innerHTML = ` <h3>Oolong</h3> <slot></slot>`; } } customElements.define("tea-card", TeaCard); const slot = document.querySelector("tea-card").shadowRoot.querySelector("slot"); console.log(slot.assignedNodes().length); console.log(slot.assignedElements().length); for (const node of slot.assignedNodes()) console.log(node.nodeName); </script>Choose an answer to see the explanation.
Question 3 of 7A price slot has the fallback Ask at the counter, and nothing is assigned to it. What does
slot.assignedNodes()return?Choose an answer to see the explanation.
Question 4 of 7Why does line 8 of this page print 0?
Read the code, then predict<script> class TeaCard extends HTMLElement { constructor() { super(); this.attachShadow({ mode: "open" }); this.shadowRoot.innerHTML = `<slot></slot>`; const slot = this.shadowRoot.querySelector("slot"); console.log("In the constructor:", slot.assignedElements().length); } } customElements.define("tea-card", TeaCard); </script> <tea-card> <p>Floral</p> </tea-card> <button>Count the notes</button> <script> const slot = document.querySelector("tea-card").shadowRoot.querySelector("slot"); document.querySelector("button").addEventListener("click", () => { console.log("On click:", slot.assignedElements().length); }); </script>Choose an answer to see the explanation.
Question 5 of 7A card attaches a closed shadow root. The page asks a slotted span for its
assignedSlot. What does it get?Choose an answer to see the explanation.
Question 6 of 7A panel puts
<slot name="heading" slot="name">inside a card. What does the card's name slot list withassignedElements(), no flatten?Choose an answer to see the explanation.
Question 7 of 7Which nodes have an
assignedSlotproperty?Choose an answer to see the explanation.
Key takeaways
slot.assignedNodes()lists every node assigned to a slot, text included, even spaces and line breaks.slot.assignedElements()lists only the elements. Use it to count or read the page's elements.- An empty slot returns an empty array.
{ flatten: true }returns what the slot shows instead: its fallback, or the content behind a slot passed in. node.assignedSlotnames the slot an element or text node landed in. It'snullwhen no slot took the node, or when the slot is in a closed root.- A component passes a slot on with
<slot name="heading" slot="name">. Give that slot its own fallback. - In a constructor that runs before the card's children are parsed, the lists are empty.
Remember the one-liner.
Ask a slot what was assigned to it, ask a node which slot it's in, and add flatten to see what the slot really shows.
Sources
The facts on this page come from these standards, docs, and source files:
- HTML Standard: The slot element, assignedNodes() and assignedElements(), WHATWG.
- HTMLSlotElement: assignedNodes() method, MDN.
- HTMLSlotElement: assignedElements() method, MDN.
- connectedCallback timing when the document parser creates custom elements (issue 551), WICG Web Components.
- Shadow DOM v1: What elements are being rendered in a slot?, Eric Bidelman, web.dev.
- Element: assignedSlot property, MDN.
- Text: assignedSlot property, MDN.
- DOM Standard: assignedSlot and finding a slot, WHATWG.
- DOM Standard: Find flattened slottables, WHATWG.
- html_slot_element.cc, CollectFlattenedAssignedNodes(), at Chromium 158.0.8127.18, Chromium.
- Working with Shadow DOM: Accessing slotted children, Lit.
Coming next: Reacting to slotted content. Know when slotted content changes, and handle empty slots.