Skip to main content

Command Palette

Search for a command to run...

The Mutation Observer JavaScript.

Overview

Updated
3 min readView as Markdown
The Mutation Observer JavaScript.
A

I'm a software engineer who loves building cool stuff and figuring out tricky problems. I work across the full stack and always enjoy learning new tech, especially when it leads to something useful in the real world.

As a developer, it is often necessary to monitor changes in the Document Object Model (DOM) to dynamically update the user interface. The Mutation Observer API is a powerful tool that allows developers to do just that, and it comes as a successor to the now deprecated Mutation Events of DOM3.

One of the key benefits of the Mutation Observer API is its simplicity. The API is easy to use and only requires a few options to set up. For example, you can specify which elements you want to watch for changes, and what type of changes you want to be notified of. This allows you to target specific elements and changes in the DOM, which can be particularly useful when working with complex applications.

In addition, the Mutation Observer API is also highly efficient. It works by observing the DOM tree, rather than constantly polling the DOM for changes. This means that it only triggers a notification when an actual change occurs, which helps to reduce the amount of unnecessary processing.

Overall, the Mutation Observer API is a valuable tool for any developer working with dynamic user interfaces. Its ability to monitor changes in the DOM simply and efficiently makes it an ideal choice for many types of applications. So, it is important to understand and use this API in your development process.


Usage

The Mutation Observer takes a callback. The callback is executed whenever a mutation being watched occurs. We would start by creating a callback for the instance of the observer. The callback takes in two parameters a mutationList and an observer. The mutationList would store all the changes occurring to the element being watched which allows us to perform a type check to see the type of mutation that occurred.

// Called when a new change happens in the element being watched
const callback = (mutationList, observer) => {
    for(let mutation of mutationList){
        if(mutation.type === 'attributes'){
            // An attribute has been mutated e.g a classList
            // Some logic
        }else if(mutation.type === 'childlist'){
            // A child node has been mutated (added/removed)
            //  Some logic
    };
  };            
};

You would then create a variable that stores the element you will be watching and one for a config object. The config object tells the observer what changes it is supposed to watch.

const myElem = document.getElementById('targetNode');
const config = { attributes:true, childlist:true, subTree:true };

You now instantiate a new Mutation Observer and pass the callback function we created earlier as its argument.

const ourObserver = new MutationObserver(callback);

Now we can watch for changes in our myElem by calling the observe method on the ourObserver instance. The observe method accepts two arguments the element being watched and the config we created.

ourObserver.observe(myElem, config);

For any change e.g a new child element being added to myElem the callback would be fired and you can perform desired logic.

Without forgetting you can later stop the observer from watching myElem. This can be achieved by calling the disconnect method on the ourObserver instance.

/* Some time later */
ourObserver.disconnect() 
// The observer stops watching for changes

Example:

Here we watch the body for any changes in its childList and if any change occurs we can perform some logic.

// Mutation Observer setup
const callback = (mutationsList, observer) => {
    for (let mutation of mutationsList) {
        if (mutation.type === 'childList') {
            //Perform some logic
        }
    }
};
const observer = new MutationObserver(callback);

observer.observe(document.body, {
    attributes: true,
    childList: true,
    subtree: true,
});

Some use cases of the Mutation Observer API are :

  • Tracking changes to the DOM tree such as when an element is added, removed or modified.

  • When implementing real-time updates to a webpage such as when new data has been received from the server.

  • When monitoring and reporting performance metrics, such as how long it would take for changes to be made to the DOM.

Hope that was helpful. Happy coding :)

F

I never knew of this API until now, thanks for sharing!

1
M

Amazingly helpful💯I gave learnt something new

1