`slotchange` event

Note: "slotchange" does not fire when an instance of the component is first initialized.

The slotchange event fires when a slot's distributed nodes changes. For example, if the user adds/removes children from the light DOM.

const slot = this.shadowRoot.querySelector('#slot');

// ⭐️ `slotchange` event listener
slot.addEventListener('slotchange', e => {
    console.log('light dom children changed!');
});

To monitor other types of changes to light DOM, you can setup a MutationObserver in your element's constructor.

example

💾 replit

const { log } = console;

// CustomMenu
class CustomMenu extends HTMLElement {

    // connected to doc
    connectedCallback() {

        // shadow root
        const root = this.attachShadow({mode: 'open'});

        // shadow dom tree (with named slots ⭐️)
        root.innerHTML = `
        <div class="container">
            <slot name="title"></slot>
            <ul><slot name="item"></slot></ul>
        </div>
        `;

        // container (div.container)
        this.container = this.shadowRoot.firstElementChild;

        // ⭐️ shadowRoot can't have event handlers, 
        //    so using the first child.
        this.container.addEventListener('slotchange', e => {
            let slot = e.target;                // changed slot (in shadow DOM)
            log("slotchange: " + slot.name)     // ⭐️ slot name
            if(slot.name === 'item'){
                // ⭐️ slot.assignedElements() is of type `Element[]`
                let items = slot.assignedElements().map(elem => elem.textContent);
                log('items:', items);
            }
        });

    }// end: connectedCallback()

}// end: CustomMenu

// register <custom-menu> tag
customElements.define('custom-menu', CustomMenu);

Last updated