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

Hostinger image

Get n8n VPS hosting 3x cheaper than a cloud solution

Get fast, easy, secure n8n VPS hosting from $4.99/mo at Hostinger. Automate any workflow using a pre-installed n8n application and no-code customization.

Start now

Top comments (0)

Sentry image

See why 4M developers consider Sentry, “not bad.”

Fixing code doesn’t have to be the worst part of your day. Learn how Sentry can help.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay