Home > Back-end >  MutationObserver looping on new nodes
MutationObserver looping on new nodes

Time:04-14

What I'm trying to do here is to highlight some textnode by making them a "span" element. And I would it to work on newly added nodes as well when new message/comment loads. However, I found MutationObserver keeps finding newly added node. Perhaps it is because doSomething creates new node and it will be re-discovered by MutationObserver. How do I keep this from happening? Not sure if I should put MutationObserver inside EventListener but it doesnot seem to be working outside of it.

document.addEventListener('DOMContentLoaded', function() {
    var allTextNodes = textNodesUnder(document.body);
    doSomething(allTextNodes);

    // Select the node that will be observed for mutations
    const targetNode = document.body;

    // 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) {
        function scanning(el) {
            // el.style.visibility = "hidden";
            var newTextNodes = textNodesUnder(el);
            doSomething(newTextNodes);
        }
    };

    // Create an observer instance linked to the callback function
    const observer = new MutationObserver(callback);

    // Start observing the target node for configured mutations
    observer.observe(targetNode, config); 
    //observer.disconnect(); //will not work if disconnect here
});

function doSomething(node) {
    var newItem = document.createElement("SPAN");
    newItem.style.backgroundColor = "red";
    var textnode = document.createTextNode(node.textContent);
    newItem.appendChild(textnode);
    node.replaceWith(newItem); 
}

CodePudding user response:

Your MutationObserver callback gets called every time you change the contents of the node, including the times that you do so within the callback itself. Before making changes within the callback, call observer.disconnect(), then reconnect using observe after making your changes:

const callback = function(mutationsList, observer) {
    function scanning(el) {
        observer.disconnect();
        // el.style.visibility = "hidden";
        var newTextNodes = textNodesUnder(el);
        doSomething(newTextNodes);
        observer.observe(targetNode, config);
    }
};
  • Related