Web Development
4 mins read
June 29, 2025
Mutation Observer is a valuable tool for web developers who need to track and respond to changes in the DOM (Document Object Model). It allows you to observe additions, removals, or modifications of nodes in a web page without constantly polling the DOM.
const observer = new MutationObserver(callback);
observer.observe(targetNode, config);
`callback` is the function that runs when a mutation is detected. `targetNode` is the DOM element to observe. `config` specifies what types of changes to monitor (e.g., child list, attributes, etc.).
const target = document.getElementById('content');
const config = {
childList: true,
subtree: true
};
const callback = function(mutationsList) {
for (const mutation of mutationsList) {
if (mutation.type === 'childList') {
console.log('A child node has been added or removed.');
}
}
};
const observer = new MutationObserver(callback);
observer.observe(target, config);
In this example, we observe a container element with ID `content`. Whenever nodes are added or removed inside it (even in nested elements due to `subtree: true`), a message is logged to the console.
Always remember to disconnect your observer when it's no longer needed. This avoids memory leaks and improves performance.
observer.disconnect();
Mutation Observer is a powerful yet underused API that allows your applications to react to real-time DOM changes. Whether you're enhancing user experience or tracking dynamic content, understanding how to use this API effectively can give your frontend code a significant boost.