Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

 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>
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading