Search code examples
javascriptdomdom-eventsmutation-observers

Which event type I have to register on element to track adding subelements


I am lookig for the way how to be informed about element has been added to my div.

The style element is added by 3rd party component and I just know into which element will be added. I am able to track this down with DevTools with DOM breakpoint on my div, but it is probably internal feature of Chrome.

Is there a way how to listen on fired event related to direct subtree modification? Something like this:

document.getElementById("my-div").addEventListener("subtree-modification", function(event) { ... my event handler });

I found information about MutationObserver in the doc. Is it the way forward? Can you provide me some example?


Solution

  • A MutationObserver will work. (In contrast, mutation events via addEventListener are deprecated and slow, best to avoid them.) For example:

    console.log('script start');
    const myDiv = document.getElementById("my-div");
    
    new MutationObserver((mutations, observer) => {
      console.log('Change observed');
      // Once the change is seen, don't need the observer anymore
      observer.disconnect();
    })
      .observe(myDiv, { childList: true });
    
    
    setTimeout(() => {
      myDiv.appendChild(document.createElement('span')).textContent = 'span content';
    }, 3000);
    <div id="my-div">my div </div>

    The childList: true will watch for changes to any direct children of the observed element. If you want to watch for changes to any descendant, use subtree: true as well:

    { childList: true, subtree: true }
    

    But deep observers are expensive - remember to remove them once they've accomplished what you need.