Element โฉ assignedSlot: HTMLSlotElement - slot that element is assigned to.
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.
constslot=this.shadowRoot.querySelector('#slot');// โญ๏ธ `slotchange` event listenerslot.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.
const { log } = console;// CustomMenuclassCustomMenuextendsHTMLElement {// connected to docconnectedCallback() {// shadow rootconstroot=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 nameif(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> tagcustomElements.define('custom-menu', CustomMenu);
// โญ๏ธ elem.$('div')Element.prototype.$=function(selector){returnthis.querySelector(selector);};// add 3 new menu items every sec['Lollipop','Apple','Milk Shake'].forEach((text, i) => {setTimeout(() => {customMenu.insertAdjacentHTML('beforeEnd',`<li slot="item">${text}</li>` ) },1000+ i *1000);})// change menu title in 4ssetTimeout(() => {customMenu.$('[slot="title"]').innerHTML ="New menu โญ๏ธ";},4000);