javascript detect when a certain element is removed

牧云@^-^@ 提交于 2020-05-26 07:20:06

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!