Suppose we have a custom element to use in this way:
<list-image>
<img src="" />
....
</list-image>
where list-image displays img tags in a slider way. If the user of component inserts an img tag with
document.querySelector('list-image').insertAdjacentHTML('beforeend', '<img src="..." />');
is it possible for the component to know the new element img?
A child is an element that is directly below and connected to an element in the document tree.
Use the querySelectorAll method to get all child elements by tag name. For example, document. querySelectorAll('#parent div') selects all of the div elements that are descendants of an element with an id of parent .
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>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With