MutationObserver Guide: Detect DOM Changes in JS & React
A third-party script injects a widget into your page, and you need to run code the moment it appears. You don't control that script, so there is no callback to hook into. The usual answer is a setInterval that checks for the element every 100 milliseconds. It works, but it wastes work on every tick, it fires late, and nobody ever removes it.
The MutationObserver API solves this properly. You tell the browser which part of the DOM to watch and what kind of change you care about, and it calls your function when that change happens. No polling, no guessing, and no deprecated events.
This MutationObserver guide explains how the API works, which options matter, and where it surprises people. It then builds practical tools in vanilla JavaScript (a waitForElement helper, an attribute watcher, a handler for dynamically added elements) and shows how to use MutationObserver in React safely, with a reusable hook, a useSyncExternalStore variant, and tests.
It is the third member of an observer family we have covered. ResizeObserver reports size changes, and IntersectionObserver reports visibility changes. MutationObserver reports changes to the DOM itself.
According to MDN's MutationObserver reference, the interface lets you watch for changes to the DOM tree and receive notifications through a callback. It is the modern replacement for the old Mutation Events such as DOMNodeInserted, which are deprecated.
A MutationObserver can report three kinds of change:
Child list changes: nodes were added to or removed from an element.
Attribute changes: an attribute on an element was set, changed, or removed.
Character data changes: the text content of a text node (or comment) changed.
Two properties of the API shape how you use it:
Callbacks are asynchronous and batched. The browser collects records of what changed and delivers them together in a microtask, after the current script finishes. Your callback does not run in the middle of someone else's DOM update. MDN's microtask guide explains the timing.
It reports changes, not the current state. The observer does not fire for content that already exists when you start observing. If you need to handle existing elements too, process them first, then observe.
What it does not detect
Many "something changed" situations are not DOM mutations:
Size changes belong to ResizeObserver.
Visibility changes belong to IntersectionObserver.
What a user types into an input. The valueproperty is not an attribute, so typing produces no mutation. Use the input event.
Computed CSS changes such as a media query switching a layout. Only edits to the style or class attributes are visible to the observer.
Canvas drawing and other pixel-level changes.
Changes inside a shadow tree when you observe the host element with subtree. A shadow root is a separate tree, so observe it directly (open shadow roots expose element.shadowRoot).
The Anatomy: Constructor, observe() and Records
const observer = new MutationObserver((records, observer) => {
for (const record of records) {
console.log(record.type, record.target);
}
});
observer.observe(targetNode, { childList: true, subtree: true });
An array of attribute names to watch (all attributes if omitted)
attributeOldValue
Record the attribute's previous value
characterData
Changes to the data of text nodes
characterDataOldValue
Record the previous text
subtree
Extend all of the above to every descendant, not just the target
Two rules from MDN are worth memorizing:
At least one of childList, attributes, or characterData must effectively be on. If nothing would be observed, observe() throws a TypeError.
attributes defaults to true when you supply attributeFilter or attributeOldValue, and characterData defaults to true when you supply characterDataOldValue. You don't need to repeat them.
observe(target, options) starts watching. You can call it on several targets with the same observer.
disconnect() stops all observation and discards queued records.
takeRecords() returns the queued records immediately and empties the queue, so the callback will not receive them.
Behaviors That Surprise People
Your own changes trigger the observer
If your callback modifies the DOM it is observing, the observer reports those changes too, which calls your callback again. An observer that sets an attribute on every attribute change loops forever. Section "Avoiding Feedback Loops" below shows the fix.
The callback sees the current DOM, not a snapshot
Because records are batched, several changes can happen before your callback runs. If an attribute changed twice, you get two records, but target.getAttribute(name) returns only the final value in both cases. When you need the sequence, enable attributeOldValue and read record.oldValue.
addedNodes contains nodes, not just elements
An added node can be a text node or a comment. A node you care about can also be a descendant of an added node, for example when a framework inserts a whole <section> containing the element you want. Always check node instanceof Element, then test both the node itself and its descendants.
Text changes come in two flavors
Setting element.textContent = "new" removes the old children and adds a new text node, so it produces a childList record. Changing an existing text node's data produces a characterData record. To catch both, observe with childList, characterData, and subtree.
Removed subtrees are tracked briefly
MDN notes that if a descendant of the target is removed, changes inside that removed subtree continue to be reported until the notification about the removal has been delivered. Don't be surprised by a late record for a node that is already detached.
Observing everything is expensive
document.body with subtree, childList, and attributes all enabled will wake your callback for nearly every update on a busy page. Observe the narrowest element you can, and use attributeFilter so unrelated attribute changes are ignored.
Recipe 1: waitForElement (No More Polling)
The most useful MutationObserver helper is a promise that resolves when an element appears. It checks the existing DOM first, observes for later additions, and cleans up in every exit path.
Check first, then observe. The element may already exist, and the observer would never report it.
A timeout. Without one, a missing element leaves the observer running for the life of the page.
An AbortSignal. It lets callers cancel the wait, for example when a component unmounts. See MDN's AbortController reference.
One cleanup function that disconnects the observer, clears the timer, and removes the listener, so every exit path leaves nothing behind.
Recipe 2: Handle Elements Added Later
Server-rendered pages, partial updates, and libraries that swap HTML (such as htmx or Turbo) add elements after your initial script has run. This helper runs a handler on every matching element, existing or future:
function onElementsAdded(selector, handler, root = document.body) {
const seen = new WeakSet();
const handle = (el) => {
if (seen.has(el)) return;
seen.add(el);
handler(el);
};
root.querySelectorAll(selector).forEach(handle);
const observer = new MutationObserver((records) => {
for (const record of records) {
for (const node of record.addedNodes) {
if (!(node instanceof Element)) continue;
if (node.matches(selector)) handle(node);
node.querySelectorAll(selector).forEach(handle);
}
}
});
observer.observe(root, { childList: true, subtree: true });
return () => observer.disconnect();
}
const stop = onElementsAdded("[data-tooltip]", (el) => {
el.setAttribute("tabindex", "0");
});
The WeakSet guarantees each element is handled once even if it moves around the DOM, and it does not prevent removed elements from being garbage collected. The function returns a stop callback so callers can clean up.
Recipe 3: Watch Attribute Changes
Attributes carry a lot of UI state: data-theme, aria-expanded, hidden, class. To react to them:
const observer = new MutationObserver((records) => {
for (const record of records) {
const name = record.attributeName;
console.log(`${name}: ${record.oldValue} → ${record.target.getAttribute(name)}`);
}
});
observer.observe(document.documentElement, {
attributes: true,
attributeFilter: ["data-theme", "class"],
attributeOldValue: true,
});
attributeFilter keeps unrelated attribute changes from waking your callback. Keep in mind the batching rule above: getAttribute returns the current value, which may be newer than the record you are processing.
Recipe 4: Watch Text and Editable Content
For a contenteditable region, combine all three kinds of change and debounce the work:
Here saveDraft is your own persistence function. Typing in an editable element changes text nodes and adds or removes nodes, so all three options are needed.
Avoiding Feedback Loops
Suppose you want every newly added link to open in a new tab, and you watch target attributes to enforce it. The moment you set target="_blank", you trigger another record. The simplest fix is to discard your own changes with takeRecords() after you make them:
const observer = new MutationObserver((records) => {
for (const record of records) {
for (const node of record.addedNodes) {
if (!(node instanceof Element)) continue;
const links = node.matches("a[href]") ? [node] : node.querySelectorAll("a[href]");
links.forEach((link) => link.setAttribute("rel", "noopener"));
}
}
// Throw away the records our own edits just created
observer.takeRecords();
});
observer.observe(document.body, { childList: true, subtree: true });
Other safe patterns include observing only attributes your code never writes (via attributeFilter), keeping a guard flag, or calling disconnect() before your edits and observe() again afterwards. Choose whichever keeps the intent clearest.
When to Use MutationObserver (and When Not To)
Good fits:
Waiting for elements injected by code you don't control, such as embeds, widgets, or third-party scripts
Enhancing content that HTML-swapping libraries add after load
Syncing UI with attributes set by other scripts, such as a theme toggle
Autosaving or analyzing editable content
Test utilities and browser extensions that must react to arbitrary pages
Poor fits:
Reacting to your own React or framework state. Use state and effects instead.
Measuring size or detecting visibility. Use ResizeObserver or IntersectionObserver.
Tracking form input. Use the input and change events.
Responding to CSS media changes. Use matchMedia.
Use observers to add behavior to your own pages. Don't use them to hide, alter, or automatically interact with ads, consent prompts, or other content supplied by third-party providers. That can break those providers' rules.
Using MutationObserver in React
React manages the DOM for you, which makes a raw DOM watcher feel out of place. It is still the right tool in a few cases: observing DOM that React did not create (an embedded script's output, a widget, or content injected by a browser extension) and bridging to external attributes.
The key rule: do not mutate DOM nodes that React renders. React expects to own them. The React documentation on manipulating the DOM with refs describes how to safely work with nodes outside React's control. The safest pattern is to render an empty container with no React children, let outside code fill it, and observe it.
A callback ref stored in state. The effect re-runs when the element mounts, unmounts, or changes.
A ref for the callback. Inline callbacks change every render. Storing the latest one in a ref means the observer is not torn down and rebuilt each time.
Primitive dependencies. Passing { childList: true } inline creates a new object every render, so the hook depends on its individual values instead.
Cleanup. The effect returns disconnect(), which also handles React Strict Mode's double-invoked effects in development.
SSR safety. The observer is created only inside an effect. In the Next.js App Router, components that use hooks need the "use client" directive.
loadEmbedScript stands in for whatever code loads your provider's script and points it at the container. React renders #embed-root with no children, so the provider can add nodes freely without conflicting with React's reconciliation, and the observer tells React when content has arrived.
Variant: mirror an external attribute with useSyncExternalStore
When you want to read a value that other code changes, such as the data-theme attribute on <html>, React's built-in subscription primitive is a better fit than a hand-written hook. See the React reference for useSyncExternalStore, and our explainer on it for why it avoids tearing during concurrent rendering.
The third argument is the server snapshot, so the component renders the same markup on the server and during hydration, then updates when the real attribute is known.
Testing MutationObserver Code
Good news: jsdom, the DOM used by Jest and Vitest's jsdom environment, implements MutationObserver, so you can test with the real API instead of a mock. Callbacks run as microtasks, so await the result.
import { beforeEach, expect, test } from "vitest";
import { waitForElement } from "./waitForElement";
beforeEach(() => {
document.body.innerHTML = "";
});
test("resolves when the element is added later", async () => {
const pending = waitForElement("#late");
const el = document.createElement("div");
el.id = "late";
document.body.append(el);
await expect(pending).resolves.toBe(el);
});
test("resolves immediately when the element already exists", async () => {
document.body.innerHTML = '<div id="here"></div>';
await expect(waitForElement("#here")).resolves.toBeInstanceOf(HTMLElement);
});
test("rejects after the timeout", async () => {
await expect(waitForElement("#missing", { timeout: 50 })).rejects.toThrow(
"Timed out"
);
});
For React components, use React Testing Library's waitFor or findBy* queries when the DOM change happens outside React's control. Unit tests prove your logic, but verify real behavior in a browser too, especially for third-party scripts that behave differently in production.
MutationObserver vs. Other Approaches
Tool
Detects
Use it when
MutationObserver
DOM structure, attribute, and text changes
You need to react to DOM changes you don't control
ResizeObserver
Element size changes
Layout depends on an element's own dimensions
IntersectionObserver
Visibility within a root
Lazy loading, sentinels, scroll reveal
Polling with setInterval
Anything, badly
Almost never: it wastes work and reacts late
Mutation Events (DOMNodeInserted)
Legacy DOM changes
Never: they are deprecated
Framework state and effects
Your own app's changes
The change originates in your own components
Performance Tips
Narrow the target. Observe the smallest container that can contain the change, not document.body.
Filter attributes. Use attributeFilter so unrelated attribute updates don't invoke your callback.
Keep the callback light. Batch work and defer expensive operations, such as with a debounce.
Disconnect when done. One-time waits should stop observing as soon as they succeed, time out, or are canceled.
Skip records you don't need. Return early for node types or targets that don't match.
Avoid observing from many components. If dozens of components need the same signal, share one observer and fan out the result.
SEO and Accessibility Notes
Don't hide essential content behind injected DOM. Content that appears only after client-side scripts run may be discovered later or less reliably by search engines. Google's JavaScript SEO basics describes how rendering works. Keep important text in the initial HTML.
Announce dynamic changes. When your observer reveals or injects content, use role="status" or aria-live="polite" so assistive technology users know something changed.
Preserve focus. Don't move keyboard focus just because content arrived.
Keep semantics intact. If you enhance injected elements, such as adding tabindex or ARIA attributes, make sure the result is keyboard accessible.
Common Mistakes and How to Fix Them
Expecting a callback for content that already exists. The observer only reports changes. Handle existing nodes first, then observe.
Modifying the observed DOM inside the callback without a guard. This creates infinite loops. Use takeRecords(), a flag, or a narrower attributeFilter.
Checking only addedNodes entries themselves. The element you want may be nested inside an added wrapper. Test the node and its descendants.
Assuming every added node is an element. Text nodes and comments appear in addedNodes. Check instanceof Element.
Reading getAttribute as if it were the value at that record. Batching means you may see a newer value. Use attributeOldValue when the sequence matters.
Observing document.body with every option on. This is a frequent cause of sluggish pages. Narrow the target and options.
Forgetting to disconnect. A forgotten observer keeps running. Disconnect on success, timeout, abort, and unmount.
Mutating React-rendered nodes from the observer callback. React will not know about those changes. Render an empty container and observe that instead.
Using it for form input. Typing changes the value property, which is not a DOM mutation. Listen to input events.
Frequently Asked Questions
What is MutationObserver used for?
It detects changes to the DOM, such as nodes being added or removed, attributes changing, or text being edited, without polling. Common uses include waiting for elements injected by other scripts, enhancing dynamically added content, and reacting to attributes changed by external code.
Is MutationObserver synchronous?
No. The browser collects mutation records and delivers them to your callback in a microtask after the current script completes. Several changes can arrive in a single callback.
How is MutationObserver different from Mutation Events?
Mutation Events such as DOMNodeInserted fire synchronously on each change and are deprecated. MutationObserver batches records and delivers them asynchronously, which is far more efficient and is the recommended approach.
Can MutationObserver detect changes to an input's value?
No. Typing changes the value property, which is not an attribute. Use the input or change event. MutationObserver would only report the valueattribute if code changed it with setAttribute.
Does MutationObserver work inside shadow DOM?
Observing a host element with subtree does not cross into its shadow tree. Observe the shadow root itself, which is available as element.shadowRoot for open shadow roots.
How do I stop an infinite loop in a MutationObserver callback?
The loop happens because your own DOM edits create new records. Call observer.takeRecords() after making your edits, observe only attributes you never write, or use a guard flag.
Can I use MutationObserver in React?
Yes, for DOM React does not control, such as output from third-party embeds. Create the observer in an effect, observe a node obtained through a ref, and disconnect in cleanup. For your own state, use React state and effects instead.
Key Takeaways
MutationObserver replaces polling and deprecated Mutation Events with batched, asynchronous notifications about DOM changes.
Choose options deliberately: childList, attributes, and characterData decide what is reported, and subtree and attributeFilter decide where.
Records describe changes, not current state, so handle existing nodes first and use oldValue when order matters.
Avoid feedback loops with takeRecords(), guards, or narrower filters.
A waitForElement helper with a timeout and abort support covers the most common need.
In React, observe DOM that React doesn't own, store the node in state, create the observer in an effect, and always disconnect. For reading external attributes, prefer useSyncExternalStore.
Observe narrowly, disconnect promptly, and keep essential content in your initial HTML.