Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mutation Observer fails to detect element's dom removal

So, I thought this was going to be pretty straight forward, there used to be a DOMNodeRemoved event, but that's deprecated, instead, MutationObserver should be used, the thing is, it doesn't fire, even whith the appropiate configuration.

According to this article about migrating from mutating events to mutation observers the configuration to detect dom removal of a node is { childList: true, subtree: true }, and that fits giving that childList is obligatory and subtree means it will capture mutations to not just target, but also target's descendants are to be observed according to the mdn article.

Anyway, I've made a jsfiddle of the problem, it's pretty straight forward, the <button> removes the <div> and the observer should log the mutation records, but it doesn't, see if you can figure it out :)

HTML

<div>Oh my god karen, you can't just ask someone why they're white.</div>
<button>^Remove</button>

JavaScript

div = document.querySelector("div");
callback = function(records){
    console.log(records);
}
config = {
    childList:true,
    subtree:true
}
observer = new MutationObserver(callback);
observer.observe(div,config);

button = document.querySelector("button");
button.addEventListener("click",function(){
    div.parentNode.removeChild(div);
});

Thanks!

like image 936
undefined Avatar asked Feb 19 '15 03:02

undefined


1 Answers

As the names suggest childList only captures changes to list of immediate children of an observed node and subtree extends any specified criteria to all descendants (it doesn't do anything on its own).

But you are doing neither. You are removing the observed node itself while leaving its descendants unchanged.

Simply observing div.parentNode instead should solve your problem.

like image 187
the8472 Avatar answered Sep 28 '22 04:09

the8472