Detect If Element Removed from DOM with Javascript

javascript
Published on January 13, 2021

We can detect whether an element has been removed DOM using the MutationObserver object. MutationObserver provides the ability to observe for changes being made to the DOM tree.

Example

Consider the below markup where there is an element #parent containing #child. We would like to know when #child is removed from the DOM.

<div id="parent">
	<div id="child">Child</div>
</div>
const observer = new MutationObserver(function(mutations_list) {
	mutations_list.forEach(function(mutation) {
		mutation.removedNodes.forEach(function(removed_node) {
			if(removed_node.id == 'child') {
				console.log('#child has been removed');
				observer.disconnect();
			}
		});
	});
});

observer.observe(document.querySelector("#parent"), { subtree: false, childList: true });
  • A new MutationObserver object is created. The observe() method starts observing DOM mutations taking #parent as the target. Note that the target cannot be the element which is to be removed.
  • observe() method accepts various options as parameter. In this case 2 options are passed.
  • subtree: false signifies that only the direct children of the target will be monitored. If we wish to monitor the entire tree of the target — children, grand-children, grand-grand-children, etc — then we would use subtree: true.
    Note: Set this to false if the element to be removed is a direct child of the target as monitoring the entire tree can be expensive.
  • childList: true signifies that addition & removal of child nodes will be monitored.
  • The callback to the MutationObserver object receives an array of mutation records. Each such record contains removedNodes property that represents an array of nodes that were removed.
  • We can loop over the nodes in removedNodes to find out whether the removed node matches our given criteria (in this case we are looking if element with ID child is present).
  • Once we find that our intended element has been removed from DOM, we can stop observing mutations using disconnect() method.

Once #child has been removed, it will be detected.

// remove #child 
document.querySelector("#child").remove();

// '#child has been removed'

Browser Compatibility

MutationObserver is supported in all browsers.

Related Resources

In this Tutorial