The slotchange Event: Detecting Content Changes
You'll learn how to listen for the slotchange event to detect when Light DOM content assigned to a slot is added, removed, or replaced.
What is slotchange?
When you use slots in Web Components, the content projected into those slots can change dynamically—users might add new elements, remove existing ones, or swap content entirely. The slotchange event fires on a <slot> element whenever its assigned nodes change, giving you a hook to react to these modifications.
Think of it like a mailbox notification: you get alerted when new mail arrives or existing mail is removed, so you can take action without constantly checking.
How It Works
You attach a slotchange listener directly to a <slot> element inside your shadow DOM. The event fires when:
- Elements with matching
slotattributes are added to the Light DOM - Slotted elements are removed
- The
slotattribute on Light DOM elements changes
class MyComponent extends HTMLElement {
connectedCallback() {
this.attachShadow({ mode: 'open' });
this.shadowRoot.innerHTML = `
<slot name="content"></slot>
`;
const slot = this.shadowRoot.querySelector('slot[name="content"]');
slot.addEventListener('slotchange', (e) => {
const assignedNodes = slot.assignedNodes();
console.log('Slot content changed!', assignedNodes.length, 'nodes');
// React to changes: update counters, reflow layout, etc.
});
}
}
Practical Use Cases
Use slotchange to update badges showing item counts, re-initialize plugins when new content appears, or validate that required content exists. It's particularly useful for container components like tabs, accordions, or lists that need to adapt to dynamic content.
Key Takeaway: The slotchange event lets you respond intelligently when Light DOM content projected into your slots changes, enabling dynamic, reactive Web Components.