Understand The Mutation Observer API

Understand The Mutation Observer API

Summary:

There are cases where you need to monitor for DOM changes to perform specific actions. Just the same way we use an event listener to listen to events delivered to a target. We use the mutation observer API to observe DOM changes and then perform an action when the observed action is true.

Basic Syntax Of The Mutation Observer:

const targetNode = getElementById(#elementId);

const observerOptions = { attributes: true, childList: true }

const callback = (mutations) => {
  // do something here
}

const observer = new MutationObserver(callback);

observer.observe(targetNode, observerOptions);

observer.disconnect();

Now let’s go over the basic syntax of a mutation observer.

In the first line, we used the targetNode to select the element we want to observe for changes, in the second line we used the observerOptions to select the properties of the element we want to observe, any option we set to true will be observed as the mutation loops through. for example, when we set the attributes and childList properties to true, the mutation observer will observe these properties in the selected element.

The callback is the callback function that gets called when an observed DOM change is true. The observer constructor instantiates a new observer. Afterwards, we pass two arguments into the observe() method (the targetNode and config options) after which the mutation can start observing. Then the disconnect() method is used to stop observing.

To understand how these all work, we will be using a live demo that incorporate the different options and different cases.

Use Case;

In this case, our mutation observer will be observing two DOM changes. (1) when a childList is added to a parent element, (2) when an attribute is added or removed

const targetNode = document.getElementById("mlist");

const configOptions = { attributes: true, childList: true };

const callback = (mutations) => {
  mutations.forEach((mutation) => {
    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, configOptions);

In the above code, we used the targetNode to get the element we want to observe, then added the attributes and childList properties to the options. This means that the mutation observer will observe these attributes.

Now, for the callback function, you will notice we’re looping through the mutations argument, which is a MutationRecord object with different properties. In this case, we’re reading for the type property of the target element and logging that a child node has been added or removed.

The last code initiates the mutation. Check this codepen for a live demo

Conclusion

This covers the basic use case of the Mutation observer and what you can do with it. To learn about the different use cases, I will recommend checking this guide with several use cases and also this MDN page.