问题
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.
回答1:
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.
来源:https://stackoverflow.com/questions/33467626/javascript-detect-when-a-certain-element-is-removed