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 :)
<div>Oh my god karen, you can't just ask someone why they're white.</div>
<button>^Remove</button>
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!
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With