Hibou57
Hibou57

Reputation: 7170

Catch a single element’s own deletion event

I need to be notified of the deletion of a particular HTML DOM element.

I’m achieving this using a MutationObserver. To keep anything as simple as possible, I though it would be better to observe the target element for its own.

MutationObserver seems to not catch anything if it observes an element which gets itself deleted. Seems I have to observe(element.parentElement, {childList: true}) to catch element’s own deletion, and observe(element, {childList: true}) does not allow to catch it.

I noted observe(element, {}) is not allowed since the WhatWG specification states “If none of options’ childList, attributes, and characterData is true, throw a TypeError”. But the same specification is not clear to me about whether or not observe(element, {childList: true}) should catch element’s own deletion, although the former sentence implicitly suggest the answer to this is “no”.

Am I missing something about MutationObserver.observe? (I guess not, but better to ask). Am I wrong using MutationObserver to achieve what I need?

Upvotes: 1

Views: 52

Answers (1)

Mouser
Mouser

Reputation: 13304

You need to make an addition to your code.

Add subtree: true to options to make it look through all descendants.

Beware to add the observer to the document.body, it can make your page hang. At least this happened when using the stack snippet.

// select the target node
var target = document.getElementById('some-id');
 
// create an observer instance
var observer = new MutationObserver(function(mutations) {
  mutations.forEach(function(mutation) {
    console.log(mutation.removedNodes[0]);
  });    
});
 
// configuration of the observer:
var config = { childList: true, subtree: true };
 
// pass in the target node, as well as the observer options
var test = target.parentElement;
observer.observe(test , config);

document.querySelector("button").addEventListener("click", function(){
   target.parentElement.removeChild(target);
});
<div id="parent">
  <div id="some-id">
      test
  </div>
</div>

<button>change</button>

Upvotes: 1

Related Questions