15

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!

undefined
  • 3,949
  • 4
  • 26
  • 38

1 Answers1

17

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.

the8472
  • 40,999
  • 5
  • 70
  • 122
  • 4
    Hi, yes I figured that might be it, there is no other way? Seems like an overexpensive method if the parent has 1000 child elements to check on all of them just for one. – undefined Feb 19 '15 at 04:04
  • if you only observe childList you would have to do lots of mutations on that 1000 node long list itself for it to be costly. and if you really do that (which seems odd) you could still wrap it in another node just for the purpose of observation – the8472 Feb 19 '15 at 04:07
  • Yeah it was an exagerated example, and the wrapping in another node seems like a cool solution, thanks you! I'll mark this as answered. – undefined Feb 19 '15 at 04:08
  • 2
    Thanks for idea! But I haven't a parent, because I create element dynamically and return to *unknown thing* of framework. I'm implementing *render* function for VirtualDom ( MutationObserver still bad API to me ((( – DenisKolodin Aug 13 '16 at 07:17
  • 3
    Won't work if parent itself will be removed. You should observe `document.body` with `childList` and `subtree` options. However, I don't know, how big impact on performance it will have. – Somnium Jul 24 '17 at 19:28