直接从或作为子树的一部分将元素从DOM中删除时,是否有任何方法来获取通知?似乎唯一可用的方法仅适用于直接删除的节点,但是当包含节点的整个子树被删除时,我想收到通知。
编辑
问题似乎还没有完全解决,所以我提出了一个挑战:https://jsbin.com/winukaf
DOM看起来像这样:
<body>
<div class="root">
<div class="great-grand-parent">
<div class="grand-parent">
<div class="parent">
<div class="leaf">
Am I still here?
</div>
</div>
</div>
</div>
</div>
</body>
挑战在于通知何时删除此处的任何元素,因为这将从DOM树中删除叶节点。
答案 0 :(得分:3)
有一个名为MutationObserver的HTML5 API,它具有很好的support
这是一个例子:
// Element is the whatever subtree/element you need to watch over
var in_dom = document.body.contains(element);
var observer = new MutationObserver(function(mutations) {
if (document.body.contains(element)) {
if (!in_dom) {
console.log("element inserted");
}
in_dom = true;
} else if (in_dom) {
in_dom = false;
console.log("element removed");
}
});
observer.observe(document.body, {childList: true, subtree: true});
答案 1 :(得分:0)
您应该使用MutationObserver API完成此操作。这是适合简单情况的MDN示例:
// Select the node that will be observed for mutations
var targetNode = document.getElementsByClassName('root')[0];
// Options for the observer (which mutations to observe)
var config = {
childList: true,
subtree: true
};
// Callback function to execute when mutations are observed
var callback = function(mutationsList, observer) {
console.log('A child node has been added or removed.');
console.log(mutationsList[0]);
};
// Create an observer instance linked to the callback function
var observer = new MutationObserver(callback);
// Start observing the target node for configured mutations
observer.observe(targetNode, config);
var subElement = document.getElementsByClassName('parent')[0];
var elementToRemove = document.getElementsByClassName('leaf')[0];
var anotherElement = document.getElementsByClassName('great-grand-parent')[0];
setTimeout(function() {
subElement.removeChild(elementToRemove);
}, 500);
setTimeout(function() {
targetNode.removeChild(anotherElement);
}, 500);
// Later, you can stop observing
// observer.disconnect();
<div class="root">
<div class="great-grand-parent">
<div class="grand-parent">
<div class="parent">
<div class="leaf">
Am I still here?
</div>
</div>
</div>
</div>
</div>