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!
MutationObserver is a Web API provided by modern browsers for detecting changes in the DOM. With this API one can listen to newly added or removed nodes, attribute changes or changes in the text content of text nodes.
The MutationObserver interface provides the ability to watch for changes being made to the DOM tree. It is designed as a replacement for the older Mutation Events feature, which was part of the DOM3 Events specification.
This is done by setting the characterData property to true in the options object. Here's the code: let options = { characterData: true }, observer = new MutationObserver(mCallback); function mCallback(mutations) { for (let mutation of mutations) { if (mutation. type === 'characterData') { // Do something here... } } }
You should be able to check the addedNodes
property on each of the mutations
object to determine if elements were added. You’ll probably also want to validate that the type
is childList
.
Check out the MutationRecord page on the MDN.
Something like
var observer = new MutationObserver(function(mutations) {
var hasUpdates = false;
for (var index = 0; index < mutations.length; index++) {
var mutation = mutations[index];
if (mutation.type === 'childList' && mutation.addedNodes.length) {
hasUpdates = true;
break;
}
}
if (hasUpdates) {
function1();
}
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With