javascriptjquerydommutation-observersdom-node

Equivalent of DOMNodeInserted DOMNodeRemoved with MutationObserver?


I currently have the code:

$('.example').bind('DOMNodeInserted DOMNodeRemoved', function(event) {
    ....
});

Which works perfectly but it is not very efficient and has since deprecated. What is a better way to do this?

I have been looking into MutationObserver but this code does work?

It is giving the error "mutation.addedNodes is not a function" I would also need the removedNodes I realise.

var observer = new MutationObserver(function(mutations) {
      mutations.forEach(function(mutation) {
        mutation.addedNodes.forEach(function(node) {
          if (node.className == 'example') {
              ....
          }
        });
      });
    });
    observer.observe(document, {
      childList: true,
      subtree: true,
      attributes: false,
      characterData: false,
    });

Solution

  • .addedNodes returns a NodeList not an Array , that does not have .forEach() method. Try using Array.prototype.slice() to cast .addedNodes to an Array which has method .forEach()

    var observer = new MutationObserver(function(mutations) {
          mutations.forEach(function(mutation) {
            var nodes = Array.prototype.slice.call(mutation.addedNodes);
            nodes.forEach(function(node) {
              if (node.parentElement.className == "example") {
                  alert(node.parentElement.className)
              }
            });
          });
        });
        observer.observe(document.querySelector(".example"), {
          childList: true,
          subtree: true,
          attributes: false,
          characterData: false,
        });
    
    var el = document.createElement("div");
    el.className = "example-child";
    document.querySelector(".example").appendChild(el)
    <div class="example"></div>