slotchange Reports Assigned Elements
Listen for slotchange on shadow-DOM slots and read assignedElements() so slot membership counters stay in sync with light-DOM nodes as they move.
Code
// slotchange fires when nodes start or stop matching a slot; assignedElements()
// reports the current membership, so counters stay in sync with the light DOM.
class TabHost extends HTMLElement {
constructor() {
super();
const root = this.attachShadow({ mode: 'open' });
root.innerHTML = '<slot name="tab"></slot><slot name="panel" hidden></slot>';
for (const slot of root.querySelectorAll('slot')) {
slot.addEventListener('slotchange', () => {
console.log(slot.name || 'default', 'slot has', slot.assignedElements().length, 'elements');
});
}
}
}
customElements.define('tab-host', TabHost);
const host = document.createElement('tab-host');
const tab = document.createElement('button');
tab.slot = 'tab'; // assigning the slot attribute moves the node into that slot
tab.textContent = 'Billing';
const panel = document.createElement('section');
panel.slot = 'panel';
panel.textContent = 'Invoices';
host.append(tab, panel);
document.body.append(host);What the code does
The working surface is the class TabHost — everything else is wiring.
for (const slot of root.querySelectorAll('slot')) is the loop that carries the per-item work.
Top-level bindings host, tab, panel hold the demo state — nothing sits inside a function scope.
Points of care
- The snippet leans on
document— browser-only surfaces a bare Node process cannot provide.
Statements that matter
slot.addEventListener('slotchange', () => {
console.log(slot.name || 'default', 'slot has', slot.assignedElements().length, 'elements');
});
Interactive Tools for This Topic
Box Shadow GeneratorBuild CSS box-shadow values with offset, blur, spread, color, opacity, and inset controls, with a live preview of the result.DOM Event Propagation VisualizerVisualize DOM event capturing, targeting, and bubbling phases in real time. Toggle stopPropagation and stopImmediatePropagation to see how events traverse the tree.SRI Hash GeneratorGenerate Subresource Integrity (SRI) hashes from resource content using SHA-256, SHA-384, or SHA-512, and copy a ready-to-use script tag.
FAQ
- Does slotchange Reports Assigned Elements run in plain Node.js?
- No — it touches `document`, which exist only in the browser. Run it in a page (or the DevTools console) instead of a bare Node process.
Report a problem with this exampleOpens a pre-filled issue on GitHub.