3

Is there a way in javascript to detect when a certain HTML element is removed in javascript/jQuery? In TinyMCE I am inserting a slider, and I would like to remove the entire thing when certain elements are removed in WYSIWIG.

poashoas
  • 1,790
  • 2
  • 21
  • 44

1 Answers1

2

In most modern browsers you can use the MutationObserver to achieve this.

The way you would do it would be something like this:

var parent = document.getElementById('parent');
var son = document.getElementById('son');

console.log(parent);
var observer = new MutationObserver(function(mutations) {
  mutations.forEach(function(mutation) {
    console.log(mutation); // check if your son is the one removed
  });
});

// configuration of the observer:
var config = {
  childList: true
};

observer.observe(parent, config);

son.remove();

You can check a running example here.

Also more info on the MutaitionObserver here.

Community
  • 1
  • 1
toskv
  • 30,680
  • 7
  • 72
  • 74
  • You've send me in the right way, I was looking for browser support. MutationObserver is supported from IE11. A good fallback is addEventListener DOMNodeRemoved – poashoas Nov 02 '15 at 09:05
  • note that it only works when 'son' is 'parent' direct child. ịf 'son' is 'parent subchild, we'll have to find another way to approach it – Clite Tailor Aug 01 '17 at 16:40
  • 2
    @CliteTailor To observe the targets descendants (parent subchild), set the subtree argument to true. – Rob J Aug 09 '17 at 12:48
  • 1
    i means that even if you set the subtree to true if you want to detect 'whether' a 'certain' descendant (element) has been removed from DOM, you still have to check all of its ancestors because the mutation only contains the node which is removed directly, but not its descendants – Clite Tailor Aug 09 '17 at 16:47
  • There's a more complete example here for those who want a quick copy-paste solution: https://stackoverflow.com/a/50397148/11950764 – joe Jul 19 '20 at 03:31