Search code examples
javascriptarraysprototypenodesmutation-observers

Get last nodes of DOM mutation


I'm listening to DOM changes with DOM mutation observer like this:

var container = document.querySelectorAll("body")[0];

  var observer = new MutationObserver(function(mutations) {
    mutations.forEach(function(mutation) {
      var target = mutation.target;
      switch (mutation.type) {

        case "childList":
          Array.prototype.forEach.call(mutation.addedNodes, function(node) {
            var lastname = node.outerHTML;
            if(typeof lastname !== "undefined")
            {


             console.log(node.outerHTML);
             //this is logging nodes as array

             var textarea = document.querySelectorAll("textarea")[0];
             textarea.value =  node.outerHTML;
             //this only gives me the very last node



            }
          });


        break;
      }
    });
  });
  observer.observe(container, {
    childList : true,
    attributes : true,
    characterData : true,
    subtree : true,
    attributeOldValue : true,
    characterDataOldValue : true
  }); 

When I view the log I see an array holding all the nodes but when I try to put the nodes in a textarea only the very last one gets printed. I can change variable in target but that gives me all the HTML of the target while I only need the HTML of the last mutation. How do I get the nodes of the last mutation into the textarea ?


Solution

  • You're overwriting the value on each iteration, not adding to it. Use a variable that you add the outerHTML to, and then set the textarea value once the iteration has completed.

    var val = '';
    
    Array.prototype.forEach.call(mutation.addedNodes, function(node) {
        var lastname = node.outerHTML;
        if(typeof lastname !== "undefined") {
    
             val += lastname;
    
        }
    });
    
    document.querySelector("textarea").value = val;