Child elements in webcomponent
The solution is to use a MutationObserver on the <list-image>
custom element itself.
In the connectedCallback()
method, observe mutations on child elements:
customElements.define('list-image', class extends HTMLElement {
connectedCallback() {
var observer = new MutationObserver(function(mutations) {
mutations.forEach(function(mutation) {
//Detect <img> insertion
if (mutation.addedNodes.length)
console.info('Node added: ', mutation.addedNodes[0])
})
})
observer.observe(this, { childList: true })
}
})
function add() {
document.querySelector('list-image')
.insertAdjacentHTML('beforeend', '<img alt="TOTO" />')
}
<list-image>
<img alt="Image1">
<img alt="Image2">
</list-image>
<button onclick="add()">Add image</button>
Upadate, from this page: https://developers.google.com/web/fundamentals/web-components/examples/howto-tabs
New children will get slotted automatically and cause slotchange to fire, so not MutationObserver is needed.