'MutationObserver — only do something if nodes added, not removed
I have a MutationObserver that I'm using like so—
var config = {
attributes: false,
childList: true,
characterData: false,
subtree: true
};
var observer = new MutationObserver(function(mutations) {
//need to call function1() only when nodes are ADDED, not removed
});
var startObserving = function () {
target = document.getElementsByClassName("message-container")[0];
observer.observe(target, config);
}
I need to both add and remove elements to/from the container that the MutationObserver is watching, but I only want to execute function1() when nodes are added. Is there a way to do this? I've been reading the MDN article but can't think of a way to do this. Any help would be appreciated!
Solution 1:[1]
I prefer do this using observer options childList and subtree. Then observer filtering changes
const observer = new MutationObserver((mutations) => {
// do something
});
observer.observe(node, {
childList: true, // detecting childList changes
subtree: true // detecing in childs
});
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Micha? Adamczyk |
