How to listen for any DOM update

This article was published on May 11, 2021

For scripting purposes we might want to listen for any page update, like a node updated with an API content or something.

For that we could use MutationObserver API

// The element we want to listen
const targetNode = document.querySelector("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) {
  // Use traditional 'for loops' for IE 11
  for (const mutation of mutationsList) {
    if (mutation.type === "childList") {
      console.log("A child node has been added or removed.");
    } else if (mutation.type === "attributes") {
      console.log("The " + mutation.attributeName + " attribute was modified.");
    }
  }
};

// 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);

With this simple snippet, every time an element has been added or removed or some attribute has changed, it'll console, but of course we could trigger other actions.

Resources