Search code examples
javascriptweb-componentcustom-element

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 layout.

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?


Solution

  • 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>