Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Child elements in webcomponent

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?

like image 793
asv Avatar asked Mar 24 '17 17:03

asv


People also ask

What is a child element?

A child is an element that is directly below and connected to an element in the document tree.

How do I find my child's element name?

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 .


1 Answers

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>
like image 109
Supersharp Avatar answered Sep 30 '22 08:09

Supersharp