Search code examples
javascriptangularjsmutation-observers

Best approach for using mutationObservers on elements which get destroyed


I'm trying to run a script on an Angular 1 site, my script looks for changes in the DOM to run a function. However since it's a single page app, my preferred mutation target node can be destroyed and replaced which stops the mutationObserver from working as its target no longer exists. I feel like targeting one of the parent nodes is a bit messy as it will be picking up hundreds of mutations and looking for my preferred one.

Are there any better approaches I could use?


Solution

  • Only a single MutationObserver instance should need to be created. Before element is removed from document call observer.disconnect().

    When new element is appended to document call .observe() method of original MutationObserver instance with target element and original configuration.

    const el = "div";
    
    let i = 0;
    
    let n = 0;
    
    function create() {
    
      let div = document.createElement(el);
      div.textContent = el + " " + ++i;
      div.contentEditable = true;
      document.body.appendChild(div);
      return div
    }
    
    let div = create();
    
    function handleMutation(mutation) {
      console.log(mutation.type);
      if (++n === 3) {
        n = 0;
        observer.disconnect();
        div.parentElement.removeChild(div);
        div = create();
        // use same `MutationObserver` instance for new `<div>` element
        observer.observe(div, config);
      };
    }
    
    const observer = new MutationObserver(function(mutations) {
      mutations.forEach(handleMutation);
    });
    
    const config = {
      childList: true,
      subtree: true,
      characterData: true
    };
    
    observer.observe(div, config);