I'm hoping to do some cleanup job when an element is removed from the DOM tree, more specifically, ParentElement.removeChild(ChildElement)
. I'm wondering whether there's any event being emitted that I can listen in my code when the ChildElement
is removed?
Asked
Active
Viewed 469 times
0

Brian Tompsett - 汤莱恩
- 5,753
- 72
- 57
- 129
2 Answers
3
Yes, you can listen for manipulations to the DOM using a MutationObserver.
Example from the MDN docs:
// Select the node that will be observed for mutations
var targetNode = document.getElementById('some-id');
// Options for the observer (which mutations to observe)
var config = { attributes: true, childList: true };
// Callback function to execute when mutations are observed
var callback = function(mutationsList) {
for(var mutation of mutationsList) {
if (mutation.type == 'childList') {
console.log('A child node has been added or removed.');
}
else if (mutation.type == 'attributes') {
console.log('The ' + mutation.attributeName + ' attribute was modified.');
}
}
};
// Create an observer instance linked to the callback function
var observer = new MutationObserver(callback);
// Start observing the target node for configured mutations
observer.observe(targetNode, config);
// Later, you can stop observing
observer.disconnect();

Elliot B.
- 17,060
- 10
- 80
- 101
0
Previously you could use mutation events like DOMNodeRemoved
which were deprecated in favour of MutationObserver:
var observer = new MutationObserver((mutations) => {
mutations.forEach((mutation) => {
const removedNodes = mutation.removedNodes;
// Cast NodeList to Array to have access to .includes method
if (Array.from(removedNodes).includes(childElement)) {
console.log('childElement removed');
}
})
});
observer.observe(document.getElementById('parentElement'), {
childList: true
});

Karen Grigoryan
- 5,234
- 2
- 21
- 35