poashoas
poashoas

Reputation: 1894

javascript detect when a certain element is removed

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.

Upvotes: 3

Views: 3701

Answers (1)

toskv
toskv

Reputation: 31632

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.

Upvotes: 2

Related Questions