Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

141
Views
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.

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

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>

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!