Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

143
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda