Get Started with MutationObserver: Everything You Need to Know

The MutationObserver API allows tracking changes to the DOM tree, including when elements are added, removed, modified, or have an attribute changed. It can also track changes to an element’s contents or styles, such as the addition or deletion of text or when a style property is modified.

We’ll look at how to use the Mutation API in this article and real-world use cases to see its importance.

Mutation Observer in action

Let’s look at the Mutation Observer API in action right away:

JavaScript
// Usage const observer = new MutationObserver((mutations) => { for (const mutation of mutations) { const el = mutation.target; if (el.textContent === 'Hello!') { el.textContent = 'Welcome!'; } } }); const textEl = document.getElementById('info'); observer.observe(textEl, { childList: true }); // Test const changeText = document.getElementById('change-text'); changeText.addEventListener('click', () => { textEl.textContent = 'Hello!'; });
The displayed text is changed by Mutation Observer.
The displayed text is changed by Mutation Observer.

Create a Mutation Observer

We create a Mutation Observer using the MutationObserver() constructor. The constructor accepts a callback that will be called when a mutation is detected on an element.

The callback is passed an array of MutationRecord objects, each containing information about the particular mutation that just occurred.

JavaScript
const observer = new MutationObserver((mutations) => { for (const mutation of mutations) { // Process mutations... } });

Two essential properties that a MutationRecord object has are the target and type property.

The target property holds the element that was mutated and type contains the type of mutation that just occurred. We can use these two properties to identify what kind of mutation happened and take the appropriate action.

For instance, we can check if the mutation was an attribute change, a child node change, or a text node change and then act accordingly. type can take the following values:

  • attributes: attribute change
  • characterData: text node change
  • childList: child node change

We can then use this data to take the appropriate action in our callback. For example, if a change to an element’s child nodes is detected, we can update the UI to reflect the new changes.

JavaScript
const observer = new MutationObserver((mutations) => { for (const mutation of mutations) { const type = mutation.type; const element = mutation.target; console.log(`${mutation.type} mutation on element #${element.id}`); } });

Observe changes with Mutation Observer

Once we have created a Mutation Observer, we can use the observe() method to start observing changes in an element. The observe() method takes two arguments: the element to observe and the configuration object. The configuration object can contain options to configure what kind of mutations to watch for. These options include childList, attributes, and characterData.

For example, if we want to watch for changes in an element’s child nodes, we can set the childList option to true. Similarly, if we’re going to watch for changes to attributes and text nodes, we can set the attributes and characterData option to true respectively.

Once we have configured our Mutation Observer and started observing changes, we can react to any changes.

Stop watching for changes in element

Once we have started observing changes, we can stop watching for changes at any time by calling the disconnect() method on the Mutation Observer. This will immediately stop watching for changes in the element, and the observe() method will no longer be called. This can be useful when you no longer need to watch for changes in an element and want to free up memory and resources.

JavaScript
observer.disconnect();

Use MutationObserver in the real-world

In many cases, you may encounter an external script that brings a range of valuable features and capabilities but brings about unwanted visual effects, like displaying text with content you’d like to customize but can’t. In this type of scenario, Mutation Observer can be used as a workaround. This tool can detect when the text content is changed in the DOM and automatically replace it with something more suitable for the task.

Get all pending mutations with takeRecords()

Mutation Observer is a powerful JavaScript API that detects changes to DOM tree elements, such as added/removed components, changed attributes, altered text content, and changed styles. A practical use is to detect and customize content set by external scripts. Create a Mutation Observer with a callback function and use observe() it to start monitoring and disconnect() to end it. takeRecords() retrieves all pending Mutation Records.