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

152
Views
el elemento agregado bajo el observador de mutación arroja un error después de eliminarlo

Hola,

Tengo un código html como este

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

luego tengo este observador, por lo que se ejecuta una función si se agrega un elemento con datos agregados.

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

funciona, pero cuando elimino el elemento, aparece este error en la consola:

Error de tipo no detectado: mutación.addedNodes[0] no está definido

Violín aquí: https://jsfiddle.net/dc63r7bg/1/

¿Cómo puedo deshacerme de ese error?

Gracias.

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

0

Puede utilizar el operador de encadenamiento opcional :

 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!