Reacting to slotted content
Learn when the slotchange event fires in web components and when it doesn't, watch inside slotted content with MutationObserver, and check for empty slots.
- 01Listen for slotchangeAdd a
slotchangelistener in the constructor, read the slot again each time it fires, and say which changes fire it. - 02Know when and where it firesIt runs after your script, once per slot for that script's changes, and bubbles only inside the shadow root, through nested slots too.
- 03Handle what it missesWatch inside slotted nodes with a
MutationObserver, and decide when a slot counts as empty, with JavaScript or:has-slotted.
What is the slotchange event?
Asha writes one tasting note in the Oolong card at Leaf and Kettle: Floral. In lesson 8.3, Ravi counted the notes in the card's constructor. He got 0, because the parser hadn't read the note yet. Later, Asha adds a second note with a button. The card never finds out.
So how does a card know that its slotted content changed?
It listens for the slotchange event. A slot fires slotchange when the list of nodes assigned to it changes: a node is added, removed, or moved to another slot. In the listener, read the slot again.
Here is Ravi's card from lesson 8.3, with one listener added:
<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); slot.addEventListener("slotchange", () => { console.log("slotchange:", slot.assignedElements().length); }); } } customElements.define("tea-card", TeaCard);</script> <tea-card><p>Floral</p></tea-card><button>Add a note</button> <script> const card = document.querySelector("tea-card"); document.querySelector("button").addEventListener("click", () => { card.insertAdjacentHTML("beforeend", "<p>Sweet</p>"); });</script>- Lines 1 to 15 define the card before the browser reads it, as in lesson 8.3.
- Line 8 counts the slot's elements in the constructor. It prints
In the constructor: 0. - Line 9 listens for
slotchangeon the slot. Line 10 counts again each time it fires. - Line 17 is the card, with one note. It's on one line, with no spaces around the note, so the card has just one child. The timing section shows why that matters.
- Line 23 adds a note, Sweet, each time you click.
The console prints In the constructor: 0, then slotchange: 1. Click Add a note, and it prints slotchange: 2. The listener ran once the parser added Floral, and again for Sweet. The count is right, however the note arrived.
slotchange counts 1.Each table at Leaf and Kettle has a serving tray with a small bell under it. The bell rings when someone puts a cup on the tray or takes one off. When it rings, Ravi walks over and counts the cups. If a guest only stirs her tea, the bell stays silent. The cups on the tray are the same.
- In real life: The tray
- In JavaScript: A slot
- In real life: Putting a cup on, or taking one off
- In JavaScript: Adding or removing a slotted node
- In real life: The bell
- In JavaScript: The
slotchangeevent - In real life: Counting the cups when it rings
- In JavaScript: Reading
assignedElements()in the listener - In real life: Stirring the tea in a cup
- In JavaScript: Changing what's inside a slotted node
A slot fires slotchange when its list of assigned nodes changes. Read the slot again in the listener. The event doesn't fire for changes inside the slotted nodes, and it never leaves the shadow root.
The event is a plain Event, and you can't cancel it. You add the listener with addEventListener(), on the slot or on its shadow root. MDN also lists an onslotchange property. Every major browser has supported it since January 2020.
First comes what fires it, when it runs, and how far it travels. Then what it misses, and how to tell when a slot is empty. At the end, the kit's card shows a Tasting notes heading only when it has notes.
What changes fire slotchange?
The rule is short. A slot keeps a list of the nodes assigned to it: the list assignedNodes() returns. When that list changes, the slot fires. The DOM standard says it this way. Each time the browser assigns nodes to a slot, it compares the new list with the old one. If they differ, it signals a slot change.
So three kinds of change fire it:
- a new child of the host that the slot takes;
- a slotted child that is removed;
- a child whose
slotattribute changes, so it moves to another slot.
A change inside a slotted node leaves the list as it was. MDN warns about this: the event doesn't fire when the children of a slotted node change. Try six changes:
<tea-card> <span slot="name">Oolong</span> <p>Floral</p></tea-card><button>Make the change</button> <script src="tea-card.js"></script><script> const card = document.querySelector("tea-card"); const note = card.querySelector("p"); document.querySelector("button").addEventListener("click", () => { console.log("Clicked"); card.insertAdjacentHTML("beforeend", "<p>Sweet</p>"); });</script>The new <p> is a child of the card with no slot attribute, so the default slot takes it. The slot's list of nodes grew, so it fires.
In the tea-card.js tab, line 9 goes through the card's three slots. Line 10 gives each one a listener, and line 11 prints which slot fired. A default slot's name is an empty string, so slot.name || "default" prints default instead. In the page, line 13 is the change. It runs when you press Make the change.
When the result loads, the console already shows two lines: slotchange on the name slot and slotchange on the default slot. That's the card's first content. The next section explains it. Now press the button for each choice:
- Add a note and Remove a note each print
slotchange on the default slot. - Change its slot prints two lines: the default slot, then the price slot. Floral moves to the price line.
- Change its words, Change its class, and Add bold text inside it print only
Clicked. The result changes, but no slot fires.
Read each row across: what the page does, and whether a slot fires.
| What the page does | Does slotchange fire? | Why? |
|---|---|---|
| Adds a child to the card | Yes, on the slot that takes it. | That slot's list of nodes grows. |
| Removes a slotted child | Yes. | The slot's list shrinks. |
Changes a child's slot attribute | Yes, on the old slot and on the new one. | The child leaves one list and joins another. |
| Moves a child into another card | Yes, on both cards. | One card's slot loses it, and the other card's slot gains it. |
Sets the card's textContent, even to the same words | Yes. | It swaps the old text nodes for new ones. |
| Changes the words inside a slotted element | No. | The element is still the same node in the list. |
Changes another attribute, like class | No. | Only slot decides where a child goes. |
| Adds an element inside a slotted element | No. | Only the card's own children are slotted. |
| Changes the fallback of a slot with nothing assigned | Yes. | The DOM standard's steps for adding and removing nodes ask for it. |
Two rows may surprise you. Setting the card's textContent fires, even with the same words. As lesson 5.5 showed, textContent swaps the old text node for a new one. So the slot's list holds a different node. The last row is rare. When a slot has nothing assigned, a change to its own fallback fires too. The DOM standard's steps for adding and removing nodes ask for that.
Why it matters: put your reading code in the listener, and it runs for every change to what a slot holds. Changes inside a note need another tool. That's the MutationObserver section below. Manual slot assignment, the next lesson, fires slotchange too, when slot.assign() changes a slot's list.
When does the slotchange listener run?
Not right away. In the overview, the constructor printed first, and slotchange came later. Here is a script that makes three changes in a row:
<tea-card></tea-card> <script src="tea-card.js"></script><script> const card = document.querySelector("tea-card"); new MutationObserver((records) => { console.log(`The observer gets ${records.length} records`); }).observe(card, { childList: true }); card.insertAdjacentHTML("beforeend", "<p>Floral</p>"); card.insertAdjacentHTML("beforeend", "<p>Sweet</p>"); card.insertAdjacentHTML("beforeend", '<span slot="price">Price: 4</span>'); console.log("The script is done");</script>- Line 1 is an empty card. Line 3 loads the playground's card, whose slots print when they fire.
- Lines 6 to 8 start a
MutationObserveron the card, as in lesson 5.5. It prints how many records it gets. - Lines 10 to 12 add two notes and a price.
- Line 13 prints
The script is done.
The console prints The script is done first. Then The observer gets 3 records. Then slotchange on the default slot and slotchange on the price slot. Three changes, but only two events. The default slot got two notes, and it fired once.
slotchange for each slot that changed, all in one microtask after the script.The DOM standard explains the order. Each change to a slot's list puts that slot in a set of slots waiting to fire. A set holds each slot only once. The first change also queues a microtask: a small job that runs as soon as the current script finishes. The microtasks lesson covers that queue.
When the microtask runs, the standard's steps to notify mutation observers call every observer with its records first. Then they fire slotchange at each waiting slot. Chrome's code does the same. EnqueueSlotChangeEvent() returns early if the slot is already waiting. DeliverMutations() runs the observers, then the slot events.
Ravi takes an order at table 4: tea, then cake, then more tea. He types each item into the till. The kitchen printer doesn't print after every item. When he presses Send, it prints one ticket for table 4. If he also changed table 6, it prints one ticket for table 6 too.
- In real life: Each item Ravi types into the till
- In JavaScript: Each change to a slot's list
- In real life: The tables waiting for a ticket
- In JavaScript: The set of slots waiting to fire
- In real life: Pressing Send
- In JavaScript: The script ending, and the microtask running
- In real life: One ticket for each table
- In JavaScript: One
slotchangefor each slot
Changes made in separate tasks fire separately. A note added now and another added in a setTimeout() make two events, one for each.
Why it matters: one event can stand for many changes. So don't count events. In the listener, read what the slot holds now.
Does slotchange fire for the first content?
Yes. A new slot starts with an empty list. When it first gets nodes, its list changes, so it fires. The overview showed one order: the class came first, and the event fired once the parser added the note. Lesson 8.3 showed the other order. There, the class comes after the card, and the card is upgraded. Does the event still fire?
<tea-card> <p>Floral</p></tea-card> <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); slot.addEventListener("slotchange", () => { console.log("slotchange:", slot.assignedElements().length); }); } } customElements.define("tea-card", TeaCard); console.log("define() is done");</script>- Lines 1 to 3 are the card, written before the class.
- Line 12 counts in the constructor. The note is already there, so it prints
In the constructor: 1. - Line 13 adds the listener.
- Line 19 prints
define() is done, at the end of the script.
The console prints In the constructor: 1, define() is done, then slotchange: 1. The slot got its note when the constructor made it. The event waited for the script to end, then fired.
So one listener covers both orders. Add it in the constructor, and do your reading inside it. An early guide on web.dev says slotchange doesn't fire when a component first starts. The DOM standard says it does, and Chrome does.
How many times does it fire while the page loads? That depends on the browser. The parser may stop partway through a card, on a slow phone for example, and carry on a moment later. Each time it stops, the waiting microtasks run. So a card written over several lines may fire once, with all its notes. Or it may fire first for a line break alone, with 0 notes, and again when the notes arrive. That's why the overview writes its card on one line. And it's why the listener reads the slot again each time, and uses the latest count.
Two cases still need care:
- A listener added later, in a
setTimeout()for example, misses the first event. It has already fired. - A card that never gets content never fires at all. So make the empty state your starting state.
Does slotchange bubble?
Yes, but only inside the shadow root. The DOM standard fires slotchange with bubbles set to true, and it doesn't set composed. Lesson 5.3 showed what that means: an event that isn't composed stops at the shadow root. So a listener on the shadow root hears every slot in it. A listener on the host, in the page, hears nothing.
<tea-card></tea-card><button>Add a note</button> <script> class TeaCard extends HTMLElement { constructor() { super(); this.attachShadow({ mode: "open" }); this.shadowRoot.innerHTML = `<slot></slot>`; this.shadowRoot.addEventListener("slotchange", (event) => { console.log("The shadow root heard it from a", event.target.localName); console.log("bubbles:", event.bubbles, "composed:", event.composed); }); } } customElements.define("tea-card", TeaCard); const card = document.querySelector("tea-card"); card.addEventListener("slotchange", () => console.log("The page heard it")); document.querySelector("button").addEventListener("click", () => { card.insertAdjacentHTML("beforeend", "<p>Floral</p>"); });</script>- Line 10 listens on the shadow root, not on a slot.
- Line 11 prints the tag name of
event.target, the slot that fired. - Line 12 prints the event's
bubblesandcomposedproperties. - Line 19 is the page, listening on the card: the host.
- Line 21 adds a note when you click.
Click Add a note. The console prints The shadow root heard it from a slot, then bubbles: true composed: false. The page's listener on line 19 never prints. Chrome's DispatchSlotChangeEvent() makes the event with CreateBubble(), which gives a bubbling event that isn't composed. Bubbling and capturing covers how events travel.
slotchange starts at the slot and bubbles up to the shadow root. It isn't composed, so it stops there. The host, and the page around it, never hear it.The kitchen at Leaf and Kettle has a bell on a shelf. When it rings, everyone in the kitchen hears it: the cook, the dishwasher, and Ravi at the door. The diners in the dining room don't. If they need to know, a waiter walks out and tells them.
- In real life: The kitchen
- In JavaScript: The shadow root
- In real life: The bell on the shelf
- In JavaScript: The slot that fires
- In real life: Everyone in the kitchen
- In JavaScript: Listeners on the slot, its parents, and the shadow root
- In real life: The diners
- In JavaScript: Listeners on the host, in the page
- In real life: A waiter who walks out and tells them
- In JavaScript: The component dispatching its own event from the host
Why it matters: listen inside the component, on a slot or on its shadow root. If the page needs to know, the component can dispatch its own event from the host, as lesson 5.3 showed. Exercise 4 does that. Composed events get their own lesson in module 9.
Why is event.target another component's slot?
Bubbling matters with nested slots too. In lesson 8.3, the tea panel put its heading slot inside a card's name slot. When the page gives the panel a heading, only the panel's slot gets a new node. The card's slot still holds the same thing: the panel's slot. So does the card hear about it?
<tea-panel></tea-panel><button>Give the panel a heading</button> <script src="tea-card.js"></script><script src="tea-panel.js"></script><script> const panel = document.querySelector("tea-panel"); document.querySelector("button").addEventListener("click", () => { panel.insertAdjacentHTML("beforeend", '<span slot="heading">Oolong</span>'); });</script>- In the
tea-card.jstab, line 7 listens on the card's name slot. - Line 8 asks whether
event.targetis that same slot. - Lines 9 and 10 print what the card shows, with
{ flatten: true }from lesson 8.3. - The
tea-panel.jstab is lesson 8.3's panel, word for word. - In the page, line 9 gives the panel a heading when you click.
On load, the console prints Is the target the card's own slot? true, then The card shows: Tea of the day. That's the card's slot getting the panel's slot. Now click the button. It prints Is the target the card's own slot? false, then The card shows: Oolong.
Chrome fired one slotchange, at the panel's slot. On its way up, the event passed through the card's slot. Here's why. When the DOM standard builds an event's path, the next stop above a slotted node is its slot, not its parent. The panel's slot is slotted into the card's slot. So the card's listener runs, with event.target set to the panel's slot.
Why it matters: in a slotchange listener, read the slot you hold, not event.target. Add { flatten: true } to see past a slot passed in.
How do you watch changes inside slotted elements?
slotchange watches a slot's list. It never looks inside the nodes on it. Sometimes a card needs that too: it reads a note's words, or one of its attributes. That's a job for a MutationObserver on the host. Lesson 5.5 built one: an object the browser calls when part of the page changes. Its options say what to watch. Here are both, side by side:
<tea-card> <p>Floral</p></tea-card><button id="words">Change the words</button><button id="class">Change the class</button> <script> class TeaCard extends HTMLElement { constructor() { super(); this.attachShadow({ mode: "open" }); this.shadowRoot.innerHTML = `<slot></slot>`; this.shadowRoot.addEventListener("slotchange", () => console.log("slotchange")); new MutationObserver((records) => { for (const record of records) console.log("The observer saw:", record.type); }).observe(this, { childList: true, subtree: true, characterData: true, attributes: true, }); } } customElements.define("tea-card", TeaCard); const note = document.querySelector("p"); document.getElementById("words").addEventListener("click", () => { note.textContent = "Sweet"; }); document.getElementById("class").addEventListener("click", () => { note.setAttribute("class", "big"); });</script>- Line 13 listens for
slotchangeon the shadow root. - Lines 14 to 21 start an observer on the card itself,
this. Line 15 prints each record's type. - Lines 17 to 20 are the options.
childListreports added and removed children, andsubtreelooks inside them too.characterDatareports edited text, andattributesreports changed attributes. - Lines 27 to 32 change the note's words, or its class, when you click.
On load, the console prints slotchange once, for the first note. Click Change the words. Only the observer prints: The observer saw: childList. textContent swapped the note's text node, so the record is a childList record inside the note. Click Change the class, and it prints The observer saw: attributes. slotchange stays quiet both times.
Both watch the card's content, from different places. The observer watches the light DOM: the card's own children, and with subtree, everything inside them. slotchange watches the slots, in the shadow tree. So each one sees changes the other can't. Sort them yourself:
- A new
<p>added to the card - A note removed from the card
- A note's
slotattribute changed - New words in a note
- A new
classon a note - A
<b>added inside a note - A comment added to the card
- The fallback of an empty slot changed
- A heading given to the panel around the card
The card has a default slot with a slotchange listener, and an observer on itself with childList, subtree, characterData, and attributes. Sort each change.
The bell under the tray rings when a cup comes or goes. It can't tell when someone adds honey to a cup. For that, Leaf and Kettle has a taster. She looks into every cup on the tray and notices each change inside it.
- In real life: The bell under the tray
- In JavaScript:
slotchange - In real life: The taster
- In JavaScript: A
MutationObserveron the host - In real life: Looking into every cup
- In JavaScript: The
subtreeandcharacterDataoptions - In real life: A cup topped up with honey
- In JavaScript: New words in a slotted note
Why it matters: start with slotchange. Add an observer only when the inside of slotted nodes matters, and ask only for what you need, as lesson 5.5 advised. In a real component, start it in connectedCallback() and stop it in disconnectedCallback(), as lesson 5.5 did. This example starts it in the constructor to stay short.
Why two tools, and not one callback? Custom elements have no callback for "my children changed". WICG issue 809 asks for one. It notes that people attach mutation observers everywhere instead.
How do you check if a slot is empty?
Lesson 8.1 showed a trap. A card written over several lines has line breaks between its tags. They're text nodes, so the default slot takes them. Its fallback hides, though the card looks blank. So "empty" can mean two things:
- Nothing is assigned.
assignedNodes()returns an empty array, and the fallback shows. - Nothing worth showing is assigned: only spaces and line breaks, or nothing at all.
For the tea card's notes, Asha means the second. Here is a check for it. Try five cards:
<tea-card></tea-card> <script> class TeaCard extends HTMLElement { constructor() { super(); this.attachShadow({ mode: "open" }); this.shadowRoot.innerHTML = `<slot>No tasting notes yet</slot>`; } } customElements.define("tea-card", TeaCard); const slot = document.querySelector("tea-card").shadowRoot.querySelector("slot"); const hasNotes = slot .assignedNodes() .some((node) => node instanceof Element || node.textContent.trim() !== ""); console.log("Nodes:", slot.assignedNodes().length); console.log("Has notes:", hasNotes);</script>Nothing is assigned. The slot shows No tasting notes yet, and the check finds no notes.
- Lines 14 to 16 go through the slot's nodes.
some()returnstrueif any node passes the test. - A node passes if it's an element, or text with real words in it.
trim()cuts spaces and line breaks off both ends of a string. So text that is only whitespace becomes"". - Lines 17 and 18 print the number of nodes and the check's answer.
Nothing and A comment print Nodes: 0 and show the fallback. A space prints Nodes: 1 but Has notes: false, and the card looks blank. Plain text and A paragraph print Has notes: true.
assignedElements().length > 0 is a shorter check. It works for notes written as tags. But it misses notes written as plain text, like the Plain text choice. Pick the check that fits your slot.
What is :has-slotted?
:has-slotted is a CSS pseudo-class. It matches a slot that has nodes assigned to it. You write it in the shadow root's styles, as slot:has-slotted. A slot with nothing assigned doesn't match, and its fallback is what shows.
It asks the same question as assignedNodes().length > 0. The CSS Shadow spec says a single whitespace text node is enough to make it match. That's on purpose, so it agrees with assignedNodes(). MDN notes it too. So it can't tell a blank-looking card from a full one.
Ravi's car has a sensor in the passenger seat. If anything is on the seat, a light asks for a seat belt. Put a bag of tea there, and the light comes on. The sensor can't tell a bag from a person. To know who's really there, Ravi has to turn and look.
- In real life: The passenger seat
- In JavaScript: A slot
- In real life: Anything on the seat
- In JavaScript: Any assigned node
- In real life: A bag of tea on the seat
- In JavaScript: A text node of spaces and line breaks
- In real life: The seat belt light
- In JavaScript:
:has-slotted - In real life: Ravi turning to look
- In JavaScript: Your own JavaScript check
Read each row across: what the card holds, and what each way of checking says.
| What's inside the card | Does the fallback show? | Does :has-slotted match? | Does the notes check find notes? |
|---|---|---|---|
| Nothing | Yes. | No. | No. |
| Only spaces or line breaks | No. The card looks blank. | Yes. A text node of spaces counts. | No. It skips spaces and line breaks. |
| Only a comment | Yes. | No. Comments are never slotted. | No. |
| Plain text | No. | Yes. | Yes. |
| A paragraph | No. | Yes. | Yes. |
Support is thin. Firefox has supported :has-slotted since Firefox 136. Chrome has it only behind an experimental flag, and Safari doesn't support it. So test for it first:
<tea-card> </tea-card> <script> class TeaCard extends HTMLElement { constructor() { super(); this.attachShadow({ mode: "open" }); this.shadowRoot.innerHTML = `<slot>No tasting notes yet</slot>`; } } customElements.define("tea-card", TeaCard); const slot = document.querySelector("tea-card").shadowRoot.querySelector("slot"); if (CSS.supports("selector(:has-slotted)")) { console.log("Filled:", slot.matches(":has-slotted")); } else { console.log("No :has-slotted here. Nodes:", slot.assignedNodes().length); }</script>- Line 1 is a card with one space inside.
- Line 14 asks the browser whether it knows the selector.
CSS.supports()takes the same test as@supportsin CSS, andselector()wraps a selector. - Line 15 runs where it does.
matches()says whether the slot matches. - Line 17 runs everywhere else. It counts the slot's nodes instead.
In Chrome, it prints No :has-slotted here. Nodes: 1. In Firefox, line 15 runs, and the slot matches, because one space is enough. Either way, the result is blank: the space hides the fallback. Without the check, Chrome throws a SyntaxError at matches(":has-slotted"). It says ':has-slotted' is not a valid selector.
Why it matters: keep a JavaScript check as your main one. Use :has-slotted as an extra, for CSS that only needs "is anything assigned?". Styling with it belongs to the lesson Styling slotted content.
Giving the tea card a notes heading
Now Asha's request. The kit's card from lesson 8.1 shows tasting notes in its default slot, under the price. She wants a Tasting notes heading above them, but only when there are notes. Here is the card's new markup:
<article class="card" aria-labelledby="name">
<h3 id="name"><slot name="name"></slot></h3>
<p id="price"><slot name="price"></slot></p>
<h4 id="notes" hidden>Tasting notes</h4>
<slot></slot>
</article>`;- Line 4 is the new heading. It starts
hidden. A card with nothing in its default slot never firesslotchange, so hidden has to be the starting state. - Line 5 is the default slot, for the notes.
And the new code in the class:
constructor() {
super();
this.attachShadow({ mode: "open" });
this.shadowRoot.append(template.content.cloneNode(true));
const notes = this.shadowRoot.querySelector("slot:not([name])");
notes.addEventListener("slotchange", () => this.#showNotes(notes));
}
#showNotes(slot) {
const hasNotes = slot
.assignedNodes({ flatten: true })
.some((node) => node instanceof Element || node.textContent.trim() !== "");
this.toggleAttribute("has-notes", hasNotes);
this.shadowRoot.getElementById("notes").hidden = !hasNotes;
}- Line 5 finds the default slot.
slot:not([name])means a slot with nonameattribute. - Line 6 listens for
slotchangeand calls#showNotes(), a private method. - Lines 10 to 12 are the playground's check, with
{ flatten: true }added. - Line 13 adds the
has-notesattribute to the card, or removes it.toggleAttribute()adds an attribute when its second argument istrue, and removes it when it'sfalse. - Line 14 shows or hides the heading.
Why flatten? Inside the panel from lesson 8.3, the card's default slot holds the panel's slot, and the line breaks of the panel's template. Without flatten, the panel's slot would count as a note, even with no notes. With it, the check sees the page's own notes. And the panel's slotchange bubbles through the card's slot, so the card hears it. Exercise 6 shows the bug.
Why an attribute? The page can see it. It can style tea-card[has-notes], or find the cards without notes. The card sets it, so the page should only read it. The kit's JSDoc and its manifest say so.
<tea-card name="Green tea" price="4"></tea-card><tea-card name="Oolong" price="5"> <p>Floral, with a honey finish.</p></tea-card><tea-panel> <span slot="heading">Chai</span></tea-panel><button id="add">Add a note to Chai</button><button id="check">Which cards have notes?</button> <script type="module"> import "./tea-kit/index.js"; const panel = document.querySelector("tea-panel"); const inner = panel.shadowRoot.querySelector("tea-card"); const cards = [...document.querySelectorAll("tea-card"), inner]; document.getElementById("add").addEventListener("click", () => { panel.append("Spiced, with ginger."); }); document.getElementById("check").addEventListener("click", () => { for (const card of cards) console.log(card.hasAttribute("has-notes")); });</script>- Line 1 is a card with only attributes. Lines 2 to 4 are a card with one note. Lines 5 to 7 are a panel with a heading, and no notes.
- Line 15 finds the card inside the panel's shadow root.
- Line 18 adds a note to the panel when you click Add a note to Chai.
- Line 21 prints whether each card has the
has-notesattribute.
The result shows Tasting notes above Oolong's note only. Click Which cards have notes?: it prints false, true, and false. Now click Add a note to Chai. The heading appears in the panel, above Spiced, with ginger. Check again: false, true, and true.
Common mix-ups
- "slotchange tells me when slotted text changes." No. It fires only when nodes are added, removed, or moved to another slot. New words in a note need a
MutationObserver. - "slotchange fires right away, on the line that made the change." No. It fires in a microtask, after the current script and after any observers.
- "Three changes fire three events." No. Each slot fires once for all the changes made in one script.
- "slotchange fires exactly once while the page loads." No. The parser may stop partway through a card, and the slot can fire at each stop. Read the slot again each time.
- "slotchange doesn't fire for a component's first content." No. It fires when a slot's list goes from empty to filled, in both load orders.
- "The page can listen for slotchange on the host." No. It bubbles inside the shadow root, but it isn't composed, so it stops there.
- "In a slotchange listener, event.target is always my own slot." No. With nested slots, it can be another component's slot, passing through.
- ":has-slotted means the slot looks filled." No. A single text node of spaces is enough to make it match.
- "An observer on the host sees everything slotchange sees." No. It can't see a fallback change, or content passed in from an outer component.
Practice exercises
Answer first, then use the hints. Each result runs live, so you can check yourself.
How many times does the console print slotchange?
<tea-card> <span slot="name">Oolong</span></tea-card> <script> class TeaCard extends HTMLElement { constructor() { super(); this.attachShadow({ mode: "open" }); this.shadowRoot.innerHTML = `<h3><slot name="name"></slot></h3>`; this.shadowRoot.addEventListener("slotchange", () => console.log("slotchange")); } } customElements.define("tea-card", TeaCard); document.querySelector("span").textContent = "Assam";</script>1. The name slot fires once, for its first content, after the script ends. Line 16 changes the words inside the span, which leaves the slot's list as it was.
Lines 18 to 20 add three notes to an empty card. What does the console print?
<tea-card></tea-card> <script> class TeaCard extends HTMLElement { constructor() { super(); this.attachShadow({ mode: "open" }); this.shadowRoot.innerHTML = `<slot></slot>`; const slot = this.shadowRoot.querySelector("slot"); slot.addEventListener("slotchange", () => { console.log("Notes:", slot.assignedElements().length); }); } } customElements.define("tea-card", TeaCard); const card = document.querySelector("tea-card"); card.insertAdjacentHTML("beforeend", "<p>Floral</p>"); card.insertAdjacentHTML("beforeend", "<p>Sweet</p>"); card.insertAdjacentHTML("beforeend", "<p>Honey</p>");</script>Notes: 3, once. The three changes put the slot in the waiting set once. The listener runs after the script, and counts all three notes.
Replace line 12 so the card prints "Notes:" and the number of notes each time its slot changes. Click Add a note once. What does the last line print?
<tea-card> <p>Floral</p></tea-card><button>Add a note</button> <script> class TeaCard extends HTMLElement { constructor() { super(); this.attachShadow({ mode: "open" }); this.shadowRoot.innerHTML = `<slot></slot>`; // Print "Notes:" and the number of notes each time the slot changes. } } 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" }); this.shadowRoot.innerHTML = `<slot></slot>`; const slot = this.shadowRoot.querySelector("slot"); slot.addEventListener("slotchange", () => { console.log("Notes:", slot.assignedElements().length); }); } } customElements.define("tea-card", TeaCard); document.querySelector("button").addEventListener("click", () => { document.querySelector("tea-card").insertAdjacentHTML("beforeend", "<p>Sweet</p>"); });</script>Notes: 2. The listener prints Notes: 1 for the first note, then Notes: 2 after the click adds Sweet.
Before you fix it, click Add a note once. How many lines does the console print? Then make the page hear it.
<tea-card></tea-card><button>Add a note</button> <script> class TeaCard extends HTMLElement { constructor() { super(); this.attachShadow({ mode: "open" }); this.shadowRoot.innerHTML = `<slot></slot>`; // The card doesn't tell the page anything yet. } } customElements.define("tea-card", TeaCard); const card = document.querySelector("tea-card"); card.addEventListener("slotchange", () => console.log("The notes changed")); document.querySelector("button").addEventListener("click", () => { card.insertAdjacentHTML("beforeend", "<p>Floral</p>"); });</script><tea-card></tea-card><button>Add a note</button> <script> class TeaCard extends HTMLElement { constructor() { super(); this.attachShadow({ mode: "open" }); this.shadowRoot.innerHTML = `<slot></slot>`; this.shadowRoot.addEventListener("slotchange", () => { this.dispatchEvent(new Event("notes-change")); }); } } customElements.define("tea-card", TeaCard); const card = document.querySelector("tea-card"); card.addEventListener("notes-change", () => console.log("The notes changed")); document.querySelector("button").addEventListener("click", () => { card.insertAdjacentHTML("beforeend", "<p>Floral</p>"); });</script>0. slotchange stops at the shadow root, so the page's listener never runs. The fix listens inside, on the shadow root, and dispatches a notes-change event from the host. After that, a click prints The notes changed.
Replace line 12 so the card prints its words each time they change. Click the button. What does it print?
<tea-card> <p>Floral</p></tea-card><button>Change the words</button> <script> class TeaCard extends HTMLElement { constructor() { super(); this.attachShadow({ mode: "open" }); this.shadowRoot.innerHTML = `<slot></slot>`; // Print the card's words each time they change. } } customElements.define("tea-card", TeaCard); document.querySelector("button").addEventListener("click", () => { document.querySelector("p").textContent = "Sweet"; });</script><tea-card> <p>Floral</p></tea-card><button>Change the words</button> <script> class TeaCard extends HTMLElement { constructor() { super(); this.attachShadow({ mode: "open" }); this.shadowRoot.innerHTML = `<slot></slot>`; new MutationObserver(() => console.log(this.textContent.trim())).observe(this, { childList: true, subtree: true, characterData: true, }); } } customElements.define("tea-card", TeaCard); document.querySelector("button").addEventListener("click", () => { document.querySelector("p").textContent = "Sweet"; });</script>Sweet. The click swaps the note's text node, which is a childList change inside the card. With subtree, the observer sees it and prints the card's words.
The page gives the panel a heading and no notes. Predict first: what does line 8 of the tea-card.js tab print? Then fix it.
<tea-panel><span slot="heading">Chai</span></tea-panel> <script src="tea-card.js"></script><script src="tea-panel.js"></script><tea-panel><span slot="heading">Chai</span></tea-panel> <script src="tea-card.js"></script><script src="tea-panel.js"></script>Has notes: true, though the panel has no notes. The card's default slot holds the panel's slot, an element. With assignedElements({ flatten: true }), the slot looks through it, finds nothing, and prints Has notes: false.
Check your understanding
For each question, ask two things: did the slot's list change, and where is the listener?
Question 1 of 7A card has a note in its default slot. Which line makes a slot fire slotchange?
Choose an answer to see the explanation.
Question 2 of 7What does this page print first?
Read the code, then predict<tea-card></tea-card> <script src="tea-card.js"></script> <script> const card = document.querySelector("tea-card"); new MutationObserver((records) => { console.log(`The observer gets ${records.length} records`); }).observe(card, { childList: true }); card.insertAdjacentHTML("beforeend", "<p>Floral</p>"); card.insertAdjacentHTML("beforeend", "<p>Sweet</p>"); card.insertAdjacentHTML("beforeend", '<span slot="price">Price: 4</span>'); console.log("The script is done"); </script>Choose an answer to see the explanation.
Question 3 of 7A card's class is defined after the card, and its constructor adds a slotchange listener. Does the listener run for the card's first note?
Choose an answer to see the explanation.
Question 4 of 7The page writes
card.addEventListener("slotchange", …). When does that listener run?Choose an answer to see the explanation.
Question 5 of 7A panel's slot sits in a card's name slot. The page gives the panel a heading. What is
event.targetin the card slot's listener?Choose an answer to see the explanation.
Question 6 of 7A card should notice when the words inside a slotted
<p>change. What should it use?Choose an answer to see the explanation.
Question 7 of 7A card is written
<tea-card> </tea-card>, with one space inside. In a browser with:has-slotted, does its default slot match it?Choose an answer to see the explanation.
Key takeaways
- A slot fires
slotchangewhen its list of assigned nodes changes: a child added, removed, or moved by itsslotattribute. - It doesn't fire for changes inside slotted nodes: new words, other attributes, or deeper elements.
- It runs in a microtask, after your script and after any observers, once for each slot the script changed.
- It fires for the first content too, in both load orders, once or several times while the page loads. Add the listener in the constructor, and read the slot again each time.
- It bubbles to the shadow root, but it isn't composed. The page can't hear it on the host. With nested slots, an outer component's event passes through your slot.
- A
MutationObserveron the host sees inside slotted nodes, whereslotchangecan't. assignedNodes()and:has-slottedboth count whitespace. Write your own check, and treat:has-slottedas an extra: only Firefox has it.
Remember the one-liner.
A slot rings when its list of nodes changes: read the slot again, watch inside with an observer, and decide what empty means yourself.
Sources
The facts on this page come from these standards, docs, and source files:
- HTMLSlotElement: slotchange event, MDN.
- DOM Standard: Assign slottables, WHATWG.
- DOM Standard: Signaling slot change, WHATWG.
- DOM Standard: Notify mutation observers, WHATWG.
- html_slot_element.cc, DidSlotChange() and EnqueueSlotChangeEvent(), at Chromium 158.0.8127.18, Chromium.
- mutation_observer.cc, DeliverMutations(), at Chromium 158.0.8127.18, Chromium.
- Shadow DOM v1: slotchange event, Eric Bidelman, web.dev.
- html_slot_element.cc, DispatchSlotChangeEvent(), at Chromium 158.0.8127.18, Chromium.
- event.h, Event::CreateBubble(), at Chromium 158.0.8127.18, Chromium.
- DOM Standard: Get the parent, WHATWG.
- MutationObserver, MDN.
- Need a callback for when children changed or parser finished parsing children (issue 809), WICG Web Components.
- :has-slotted, MDN.
- CSS Shadow Module Level 1: the :has-slotted pseudo-class, CSS Working Group.
- Firefox 136 release notes for developers, MDN.
- :has-slotted pseudo selector, Chrome Platform Status.
Coming next: Manual slot assignment. Choose in JavaScript which slot each child goes to, instead of using slot attributes.