When someone interacts with a webpage, the browser sends events to the relevant JavaScript code. The slotchange event happens when assigned light-DOM nodes of a slot change.
When slotchange happens
Assigned light-DOM nodes of a slot change.
You can listen for it using addEventListener(). That keeps event handling separate from HTML attributes such as onclick and works well with modern code organization.
A small working example
<sample-card id="sample-card">
<span slot="message">Original message</span>
</sample-card>
<button id="replace-message" type="button">Replace message</button>
<p id="event-status" role="status">Waiting for slotchange...</p>
<script>
customElements.define("sample-card", class extends HTMLElement {
constructor() {
super();
const shadowRoot = this.attachShadow({ mode: "open" });
shadowRoot.innerHTML = '<slot name="message"></slot>';
}
});
const sampleCard = document.getElementById("sample-card");
const messageSlot = sampleCard.shadowRoot.querySelector("slot");
const eventStatus = document.getElementById("event-status");
messageSlot.addEventListener("slotchange", (eventDetails) => {
eventStatus.textContent = "slotchange event received";
console.log(messageSlot.assignedElements());
});
document.getElementById("replace-message").addEventListener("click", () => {
sampleCard.innerHTML = '<span slot="message">Updated message</span>';
});
</script>
Reading the code
The browser listens for slotchange on the relevant target. When the event occurs, the callback receives eventDetails, updates the status message and logs the event name and target in Developer Tools.
Use a Web Component with a real shadow root and change slot assignments.
The slot element can report assignedNodes() to inspect its assigned light DOM children.
Some events need a specific browser condition, another tab or window, or a Web Component to reproduce. Read the trigger steps carefully before deciding that an event handler is not working.
Try it in your browser
Open the page, show the Console panel, and follow this test: Use a Web Component with a real shadow root and change slot assignments. Then change one thing in the example and observe whether the event still fires.
Common Beginner Mistakes
- Expecting
slotchangeto fire without its required user action or browser condition. - Use a Web Component with a real shadow root and change slot assignments.
- Adding repeated event listeners without considering cleanup or unwanted side effects.
Key Takeaways
slotchangereports assigned light-DOM nodes of a slot change.addEventListener("slotchange", ...)listens for the event on the appropriate target.- Use a Web Component with a real shadow root and change slot assignments.