DEV Community

Cover image for How to monitor changes in JavaScript?
Khwaja Billal Siddiqi
Khwaja Billal Siddiqi

Posted on

How to monitor changes in JavaScript?

For monitoring the changes that have been made to the DOM tree you can use MutationObserver.
MutationObserver is a built-in object that observes a DOM element and fires a callback when it detects a change. It provides the ability to watch for changes being made to the DOM tree and is designed as a replacement for the older Mutation Events feature.

Some common use cases for MutationObserver include:
  • Augmenting third-party libraries that modify the DOM in some way but you want to extend this further or capture something from it.
  • Reacting to changes in the DOM, such as when elements are created or when property changes occur.

To use MutationObserver, you first create an observer with a callback-function and then attach it to a DOM node. The config object specifies what kind of changes to react on, such as changes in the direct children of the node, changes in all descendants of the node, changes in attributes of the node, etc.

Here is an example adapted from MDN:
const targetNode = document.getElementById("some-id");
const config = { attributes: true, childList: true, subtree: true };

// Callback function to execute when mutations are observed
const callback = (mutationList, observer) => {
  for (const mutation of mutationList) {
    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.`);
    }
  }
};

const observer = new MutationObserver(callback);
observer.observe(targetNode, config);

// Later, you can stop observing
observer.disconnect();
Enter fullscreen mode Exit fullscreen mode
Follow me on Github & Twitter

Top comments (0)