Dharini S Dharini S - 1 year ago 79
Javascript Question

I want the mutation observer to listen if its target node is itself is removed in javascript

I am using mutation observer on a target node. It fires if any of the child nodes or properties change. But I have a case where I had to handle the target node itself being removed. This is not working. Is there a way to handle this?

Answer Source

MutationObservers can watch for 3 things:

  • An attribute change
  • A text content change
  • A child list change

Then optionally those change events can be bubbled up, so if you want to changes on both the target and all of the target's children, you can do that.

This means what you want cannot be done by listening to your target. You would need to attach an observer to the target's parent node, and listen for a childList change on the parent that removes the node you want to track.

e.g. instead of this fake example of what you were hoping for

var observer = new MutationObserver(callback);
observer(target, {
  // Fake non-existent option
  parent: true

you do

var observer = new MutationObserver(function(mutations){
   var targetRemoved = mutations.some(function(mutation){
     return mutation.removedNodes.indexOf(target) !== -1;

   if (targetRemoved) callback();
observer(target.parentNode, {
  childList: true