Search code examples
javascriptmutation-observers

added element under mutation observer throws an error after removed


Hi,

I have html code like this

<div id="box"></div>

then I have this observer so a function is executed if an element with data-added is added.

 new MutationObserver((mutations) => {
     for (let mutation of mutations) {
      if (mutation.type === 'childList' && mutation.addedNodes[0].dataset.added) {
       loadstuff();
      }
     }
    }).observe(box, {childList: true});

it works but as I remove the element I get this error on console:

Uncaught TypeError: mutation.addedNodes[0] is undefined

Fiddle here: https://jsfiddle.net/dc63r7bg/1/

How can I get rid of that error?

Thank you.


Solution

  • You can use the optional chaining operator:

    var box = document.getElementById("box");
    
    function addit() {
      box.insertAdjacentHTML('afterbegin', '<span id="elm" data-added="yes">element</span>');
    }
    
    function removeit() {
      document.getElementById("elm").remove();
    }
    
    new MutationObserver((mutations) => {
      for (let mutation of mutations) {
        if (mutation.type === 'childList' && mutation.addedNodes[0]?.dataset.added) {
          console.log('added');
        }
      }
    }).observe(box, {
      childList: true
    });
    <div id="box"></div>
    <button onclick="addit()">Add</button>
    <button onclick="removeit()">Remove</button>