Ever needed to react when the DOM changes under your feet, without polling it every few milliseconds? That's exactly what the MutationObserver API was built for.
In this article, we'll cover:
- What MutationObserver is and why it replaced the old Mutation Events
- How to configure and use it correctly
- Real-world use cases
- Common pitfalls and performance tips
๐งฉ What Is MutationObserver?
MutationObserver is a browser API that lets you watch a DOM node (and optionally its subtree) for changes โ added/removed children, attribute changes, or text content changes โ and run a callback whenever they happen.
Before it existed, developers relied on Mutation Events (DOMNodeInserted, DOMSubtreeModified, etc.), which were synchronous, fired for every single change, and could tank performance on busy pages. MutationObserver fixes this by batching changes and delivering them asynchronously, in a microtask, after the DOM has already updated.
Basic Syntax
const observer = new MutationObserver((mutationsList, observer) => {
for (const mutation of mutationsList) {
console.log(mutation.type, mutation.target);
}
});
observer.observe(targetNode, {
childList: true,
attributes: true,
subtree: true,
});
Configuration Options
childListโ watch for added/removed child nodesattributesโ watch for attribute value changessubtreeโ extend the observation to all descendants, not just the target nodecharacterDataโ watch for changes to text contentattributeOldValueโ include the previous value of changed attributescharacterDataOldValueโ include the previous text contentattributeFilterโ limit which attributes to watch, e.g.['class', 'style']
You must set at least one of
childList,attributes, orcharacterDatatotrue, otherwiseobserve()throws an error.
Stopping and Flushing
observer.disconnect(); // stop watching
const pending = observer.takeRecords(); // flush queued mutations without waiting for the callback
takeRecords() is handy right before calling disconnect(), so you don't lose mutations that were queued but not yet delivered.
๐ ๏ธ Real-World Use Cases
- Third-party widget integration โ detecting when a chat widget or ad script injects its own DOM nodes, so you can style or reposition them.
- Building UI libraries โ libraries like tooltip or modal managers use it to detect when their target element is removed from the DOM, so they can clean up listeners automatically.
- Syncing with external editors โ watching a
contenteditableelement for changes without relying oninputevents, which don't always fire consistently across browsers. - Analytics and SPA route tracking โ detecting DOM updates in apps that don't use the History API cleanly.
- Polyfills and feature detection โ reacting when specific attributes (like
disabledoraria-*) change on an element you don't control.
Example: Watching for Dynamically Added Elements
const list = document.querySelector('#items');
const observer = new MutationObserver((mutations) => {
for (const mutation of mutations) {
mutation.addedNodes.forEach((node) => {
if (node.nodeType === 1) {
console.log('New element added:', node);
}
});
}
});
observer.observe(list, { childList: true });
Example: Watching Attribute Changes
const button = document.querySelector('#submit-btn');
const observer = new MutationObserver((mutations) => {
mutations.forEach((m) => {
if (m.attributeName === 'disabled') {
console.log('Button disabled state changed:', button.disabled);
}
});
});
observer.observe(button, {
attributes: true,
attributeFilter: ['disabled'],
});
โ ๏ธ Common Pitfalls
- Forgetting to disconnect โ an observer left running on a removed element keeps references alive and can leak memory. Always call
disconnect()when the target is unmounted (in React'suseEffectcleanup, for example). - Over-observing with
subtree: trueโ watching a huge subtree for every attribute change on a busy page can get expensive. Scope your observer as narrowly as possible and useattributeFilter. - Infinite loops โ if your callback mutates the same node you're observing, you can trigger yourself repeatedly. Guard against this by disconnecting before you mutate, then reconnecting.
- Assuming synchronous delivery โ mutations are batched and delivered as a microtask, not immediately. Don't rely on the callback firing before the next line of your code runs.
โ Best Practices
- Observe the smallest possible target, not
document.body, unless you truly need to. - Use
attributeFilterinstead of watching every attribute. - Always pair
observe()with a matchingdisconnect()in cleanup code. - Prefer
MutationObserverover polling withsetIntervalwhenever you need to react to DOM changes โ it's event-driven and far cheaper.
๐งพ Final Thoughts
MutationObserver is one of those browser APIs that quietly powers a lot of the tooling we use every day โ from browser extensions to component libraries. Once you understand its configuration options and lifecycle, it becomes a reliable way to react to DOM changes without resorting to brittle polling or deprecated events.