Reputation: 63
I'm trying to use mutationsobserver to log only the added nodes. Here's what I got so far. I can't get passed this part. I'm stuck. I tried to get the NodeList index count when it first starts, and only log the newly added nodes using that but ended up failing. I have no idea how to accomplish this. I didn't know about mutation observer until this morning honestly.
Here's my current script
const targetNode = document.getElementById('team_log_actual');
// Options for the observer (which mutations to observe)
const config = { attributes: true, childList: true, subtree: true };
// Callback function to execute when mutations are observed
const callback = function(mutationsList, observer) {
for(let mutation of mutationsList) {
if (mutation.type === 'childList') {
console.log('a node added.' + mutation.target);
var html = mutation.target;
var htmlstring = JSON.stringify(html);
console.log(html)
}
}
};
const observer = new MutationObserver(callback);
observer.observe(targetNode, config);
Everytime a new one is added. I would like to stringify the added node only.
Upvotes: 1
Views: 3237
Reputation: 12796
You can use the mutation.addedNodes
to see which nodes got added to the element. If you would just like to print the innerHTML of all nodes, you could do something like:
console.log( Array.from( mutation.addedNodes ).map( node => node.innerHTML ).join('\r\n') );
This would first convert the addedNodes
(which is of type NodeList), into an array, and then map will retrieve the innerHTML for each node. You can then join it together and print out the changes.
Below code would simulate this behavior.
For the configuration, you don't have to check the attributes or the subtree, childList would do for what you want it to do
const targetNode = document.getElementById('team_log_actual');
// Options for the observer (which mutations to observe)
const config = {
attributes: false,
childList: true,
subtree: false
};
// Callback function to execute when mutations are observed
const callback = function(mutationsList, observer) {
for (let mutation of mutationsList) {
if (mutation.type === 'childList') {
console.log( Array.from( mutation.addedNodes ).map( node => node.innerHTML ).join('\r\n') );
}
}
};
const observer = new MutationObserver(callback);
observer.observe(targetNode, config);
let counter = 0;
setInterval(function() {
var span = document.createElement('span');
span.innerHTML = 'I am element ' + (++counter);
targetNode.appendChild(span);
}, 1000);
<div id="team_log_actual"></div>
Upvotes: 3