MDN โฉ
Element โฉ assignedSlot: HTMLSlotElement - slot that element is assigned to.
Note: "slotchange" does not fire when an instance of the component is first initialized.
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.
// โญ๏ธ elem.$('div')
Element.prototype.$ = function(selector){
return this.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 4s
setTimeout(() => {
customMenu.$('[slot="title"]').innerHTML = "New menu โญ๏ธ";
}, 4000);
<custom-menu id="customMenu">
<!-- โญ๏ธ light dom: slotted elements -->
<span slot="title">Candy menu</span>
</custom-menu>
<span slot="title">Candy menu</span>
inserted into title slot.
new <li slot="item">
tag inserted into item slot.
new <li slot="item">
tag inserted into item slot.
new <li slot="item">
tag inserted into item slot.
there's NOslotchange
event after 4 sec (on modifying the content of a slotted element).
If weโd like to track internal modifications of light DOM from JavaScript, use: MutationObserver.