completefrontend
Open lab My progress
THE WEB COMPONENTS FIELD GUIDE

The slot API

Learn how to get slotted elements in web components with assignedNodes(), assignedElements(), and assignedSlot, plus the flatten option and nested slots.

By the end, you can
  • 01
    Read what landed in a slotUse assignedNodes() and assignedElements(), and say why spaces and line breaks show up in one list but not the other.
  • 02
    Read what a slot showsAdd { flatten: true } to get a slot's fallback, and the content behind a slot passed in from another component.
  • 03
    Find a node's slotRead assignedSlot on elements and text nodes, and say why it can be null.

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:

Ask the slot, then ask the spanPop out in the code editor (opens in a new tab)HTML
<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>
ResultLoading…
  • Line 2 is the card's child: a span that asks for the price slot.
  • 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.

On the left, what the page wrote: <tea-card>, and under it <span slot="price">. On the right, a window called shadow, what the card wrote: <p>, and under it <slot name="price">. An arrow labelled assignedElements() curves from the slot to the span. A second arrow labelled assignedSlot curves back from the span to the slot.what the page wrote<tea-card><span slot="price">what the card wroteshadow<p><slot name="price">assignedElements()assignedSlot
Ask the slot, and assignedElements() gives you the span. Ask the span, and assignedSlot gives you the slot. The span stays the card's child the whole time.
Real-life analogyA table list and a place card

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() and slot.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
The main idea

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:

Count a slot's nodes, then its elementsPop out in the code editor (opens in a new tab)HTML
<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>
ResultLoading…
  • 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's nodeName is 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.

The default slot's nodes, in page order. The first row, labelled assignedNodes(), has five cards: #text, <p>, #text, <p>, #text, and the note 5 nodes. The second row, labelled assignedElements(), has the same five cards, but the three #text cards are crossed out, and the note says 2 elements.the default slot's nodes, in page orderassignedNodes()#text<p>#text<p>#text5 nodesassignedElements()#text<p>#text<p>#text2 elements
The line breaks and spaces between the notes are text nodes. assignedNodes() lists all five. assignedElements() drops the three text nodes and keeps the two paragraphs.
Real-life analogyUnpacking a box of tea tins

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:

Playground: what lands in the default slot?
A card with one default slot, and a script that lists what it gotPop out in the code editor (opens in a new tab)HTML
<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>
ResultLoading…
Try it yourself
5 nodes, but only 2 elements.

The line breaks and spaces around each <p> are text nodes. assignedNodes() lists them: #text, P, #text, P, #text. assignedElements() keeps the two paragraphs.

Only the card at the top changes. The script under it prints how many nodes and elements the slot got, then each node's name.
  • 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:

Reading the slot in the constructor, then on a clickPop out in the code editor (opens in a new tab)HTML
<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>
ResultLoading…
  • 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.

Real-life analogyReading the table list too early

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 slotchange event, 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:

An empty slot, with and without flattenPop out in the code editor (opens in a new tab)HTML
<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>
ResultLoading…
  • 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 prints 1.
  • 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.

Chai's price slot, with nothing assigned. First row: assignedNodes(), an arrow, and an empty card [], labelled an empty array. Second row: { flatten: true }, an arrow, and a card "Ask at the counter", labelled its fallback.Chai's price slot, with nothing assignedassignedNodes()[]an empty array{ flatten: true }"Ask at the counter"its fallback
Nothing is assigned, so 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.

Ask two spans and a line of text for their slotPop out in the code editor (opens in a new tab)HTML
<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>
ResultLoading…
  • Lines 2 and 3 are two spans. One asks for the price slot, and one for a photo slot.
  • 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 price and photo. 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.

A span slotted into a closed shadow rootPop out in the code editor (opens in a new tab)HTML
<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>
ResultLoading…
  • 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 print Inside 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.

A panel that passes its heading to a cardPop out in the code editor (opens in a new tab)HTML
<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>
ResultLoading…
  • In the tea-panel.js tab, line 8 is the key line: <slot name="heading" slot="name">. Its name makes it the panel's heading slot, for the page. Its slot attribute sends it on to the card's name slot. Its fallback is Tea of the day.
  • In the tea-card.js tab, 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:

  1. Take the nodes assigned to the slot.
  2. If there are none, take the slot's own children, its fallback, instead.
  3. Swap each node that is itself a slot in a shadow root for that slot's own list, made with these same steps.
  4. 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().

Three rows on the left. The page: <span slot="heading">. An arrow labelled assigned to points down to the panel: <slot name="heading" slot="name">. A second arrow labelled assigned to points down to the card: <slot name="name">. On the right, what the card's slot lists: with assignedElements(), a <slot> card; with { flatten: true }, a <span> card.the page<span slot="heading">assigned tothe panel<slot name="heading" slot="name">assigned tothe card<slot name="name">the card's slot listsassignedElements()<slot>{ flatten: true }<span>
The page's span is assigned to the panel's slot, and that slot is assigned to the card's. Without flatten, the card's slot lists the panel's <slot>. With { flatten: true }, it lists the span.
Real-life analogyParcel forwarding

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:

Playground: pass a heading through the panel
A panel that passes its heading to the card's name slotPop out in the code editor (opens in a new tab)HTML
<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>
ResultLoading…
Try it yourself
Without flatten, a SLOT. With it, the page's SPAN.

The card's name slot holds the panel's <slot>. flatten: true swaps that slot for what it holds: the page's span, Oolong.

Only the panel at the top changes. The tea-card.js and tea-panel.js tabs stay the same. The names line turns a list of nodes into their names, like SLOT or SPAN, or the word nothing.
  • A heading gives SLOT without flatten, and SPAN with 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:

From the page's span to the panel's slot, then the card'sPop out in the code editor (opens in a new tab)HTML
<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>
ResultLoading…
  • 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:

The kit panel's template, with three forwarding slots (tea-kit/tea-panel.js, lines 1 to 16)JavaScript
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 heading slot to the card's name slot.
  • Line 13 forwards price to price. The two names can match, or differ, as on line 12.
  • Line 14 forwards the default slot. A <slot> with no slot attribute 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:

Read the name every card shows, with flattenPop out in the code editor (opens in a new tab)HTML
<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>
ResultLoading…
  • Line 1 is a card whose name comes from its name attribute. 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), and Oolong.

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.

What each slot call returns
Which callDoes 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.

Which call lists 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>
Try it yourself
0 of 8 correct

Sort each node by the calls that list it. assignedNodes() means no options.

Choose a category for every card. You can change an answer at any time; Reset clears them all.

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 assignedSlot is still null.
  • "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.

Exercise 1 · Warm-upCount the nodes

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>
ResultLoading…

Answer, then press Check. Spacing and letter case don’t matter.

    Exercise 2 · Warm-upAn element as fallback

    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>
    ResultLoading…

    Answer, then press Check. Spacing and letter case don’t matter.

      Exercise 3 · PracticePrint each note

      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>
      ResultLoading…

      Answer, then press Check. Spacing and letter case don’t matter.

        Exercise 4 · PracticeFind the bug in the note count

        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>
        ResultLoading…

        Answer, then press Check. Spacing and letter case don’t matter.

          Exercise 5 · ChallengeRead through the panel without flatten

          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>
          ResultLoading…

          Answer, then press Check. Spacing and letter case don’t matter.

            Exercise 6 · ChallengeWhich slot holds the price?

            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>
            ResultLoading…

            Answer, then press Check. Spacing and letter case don’t matter.

              Check your understanding

              For each question, ask two things: are you asking the slot or the node, and does it need flatten?

              The slot API quiz · 7 questionsScore: first tries count
              1. 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.

              2. Question 2 of 7What does line 19 of this page print?

                Read the code, then predictPop out in the code editor (opens in a new tab)HTML
                <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.

              3. 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.

              4. Question 4 of 7Why does line 8 of this page print 0?

                Read the code, then predictPop out in the code editor (opens in a new tab)HTML
                <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.

              5. 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.

              6. Question 6 of 7A panel puts <slot name="heading" slot="name"> inside a card. What does the card's name slot list with assignedElements(), no flatten?

                Choose an answer to see the explanation.

              7. Question 7 of 7Which nodes have an assignedSlot property?

                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.assignedSlot names the slot an element or text node landed in. It's null when 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:

              Coming next: Reacting to slotted content. Know when slotted content changes, and handle empty slots.

              CompleteFrontend Clear concepts. Working examples.