0

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?

Brian Tompsett - 汤莱恩
  • 5,438
  • 68
  • 55
  • 126
Qian Chen
  • 14,824
  • 18
  • 61
  • 88

2 Answers2

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.
  • 16,012
  • 10
  • 75
  • 100
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
  • 4,829
  • 2
  • 18
  • 34