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.

TypescriptData Integrity

Code

typescriptsnippet
25 lines
// 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

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.