MutationObserver

Also known as: Mutation Observer API

On this page 7

MutationObserver is the browser JavaScript interface that lets a script watch the DOM for changes and receive a batched list of mutation records describing what changed: child nodes added or removed, attributes modified or text content rewritten. In Browser JavaScript on the Web, it is the standard replacement for the deprecated Mutation Events, and it is specified in the WHATWG DOM Living Standard, where it is also called the Mutation Observer API.

The interface solves a practical problem: modern pages are changed constantly by frameworks, third-party widgets and user actions, and code often needs to react when a specific element appears, disappears or changes state. Instead of polling the document with timers, a script registers a callback once and the browser delivers precise, asynchronous notifications at a predictable moment in the event loop.

How MutationObserver delivers DOM change records

A MutationObserver works by recording mutations into a queue and delivering them to a callback as a microtask, after the script that caused the changes has finished. The developer creates an observer with new MutationObserver(callback) and then calls observe(target, options) on one or more nodes. Each DOM change that matches the options produces a MutationRecord, and all records collected during the current task arrive together in a single callback invocation.

This batching behavior is the core design decision. If a script inserts 500 list items in a loop, the callback runs once with 500 records rather than 500 times. Because delivery happens in the microtask queue, the callback runs before the browser renders the next frame, so code can correct or annotate new content before the user sees it.

The observer exposes three methods besides the constructor. The table below summarizes what each one does and when it is used.

MethodPurposeTypical use
observe(target, options)Starts watching a node with given optionsRegister once per target element
disconnect()Stops all observation and discards pending recordsCleanup when a component unmounts
takeRecords()Returns and empties the pending record queueFlush records synchronously before disconnecting
Methods of the MutationObserver interface

Observation options and mutation record types

The options object passed to observe() defines which kinds of change are reported and how far down the tree the observer looks. At least one of childList, attributes or characterData must be true, otherwise the call throws a TypeError. Narrow options reduce the volume of records and therefore the processing cost of the callback.

OptionEffectNotes
childListReports added and removed child nodesDirect children only unless subtree is set
attributesReports attribute changesImplied when attributeFilter or attributeOldValue is set
characterDataReports text node content changesApplies to Text, Comment and similar nodes
subtreeExtends observation to all descendantsOften the main source of record volume
attributeFilterLimits reporting to listed attribute namesExample: class and aria-expanded
attributeOldValueStores the previous attribute valueAvailable as oldValue on the record
characterDataOldValueStores the previous text valueUseful for diffing text edits
Options accepted by the observe method

Each MutationRecord carries a type property with one of three values: childList, attributes or characterData. The record also exposes target, addedNodes, removedNodes, previousSibling, nextSibling, attributeName and oldValue. Reading addedNodes and removedNodes correctly matters, because they are NodeList objects that may contain text nodes and comments, not only elements.

MutationObserver answers the question whether the DOM structure changed, which distinguishes it from neighboring APIs that answer questions about visibility, size or user input. Choosing the wrong one is a common source of unnecessary complexity and poor performance.

MechanismWhat it detectsDelivery timing
MutationObserverDOM node, attribute and text changesMicrotask, batched
Mutation EventsSame changes, one event per changeSynchronous, deprecated and removed
Intersection Observer APIVisibility of an element in a viewportAsynchronous, batched per frame
ResizeObserverChanges in an element box sizeAfter layout, before paint
Event listenerUser and system events such as click or inputTask queue, one event per occurrence
Polling with timersAny condition the script checksFixed interval, wasteful
Comparison of observation and notification mechanisms

The deprecated Mutation Events, such as DOMNodeInserted, fired synchronously for every single change and propagated through the tree, which slowed down DOM operations considerably. Major browsers have removed them, and MutationObserver is the supported path. Note that MutationObserver does not fire for property changes that leave the DOM unchanged, such as typing into an input field, because the value property is not the value attribute.

Practical uses and configuration choices

MutationObserver is the right tool when code does not control the code that changes the DOM. Typical cases include browser extensions, analytics scripts, accessibility helpers and integration layers around third-party widgets. Inside a component framework that owns its own rendering, lifecycle hooks are usually simpler and more reliable.

SituationRecommended setupReason
Wait for a widget to appearchildList and subtree on a nearby container, then disconnectShort-lived observer with minimal cost
Track a toggle stateattributes with attributeFilter on one elementReports only the relevant attribute
Sanitize injected contentchildList and subtree on the insertion pointCallback runs before the next paint
Detect text edits in a contenteditable regioncharacterData, subtree and characterDataOldValueProvides old and new text for diffing
Lazy-load images on scrollIntersection Observer API insteadVisibility, not structure, is the question
Choosing an observation strategy

A sound pattern is to observe the smallest stable ancestor rather than document.body, filter records early in the callback, and call disconnect() as soon as the observer has done its job. Code that must run after a burst of changes can combine the callback with a debounce, although the built-in batching already absorbs most bursts within a single task.

Performance limits and common mistakes

The main risk is unbounded record volume. Observing an entire document with subtree: true on a page that rerenders large lists can generate thousands of records per task, and every record allocates memory. The callback itself runs on the main thread, so expensive work there directly delays rendering and input handling.

  • Infinite loops: a callback that modifies the observed subtree triggers new records; guard changes with a check or disconnect while writing.
  • Memory leaks: observers hold references to their targets until disconnected, so long-lived single-page applications must clean them up.
  • Assuming elements only: addedNodes includes text and comment nodes; filter with nodeType before calling element methods.
  • Expecting property changes: user input that changes the value property produces no record; use an input event listener instead.
  • Shadow DOM blind spots: observing a host element does not reach into its shadow root; observe the shadow root separately.

Browser support is universal across current engines, including Chromium, Gecko and WebKit, so a polyfill is no longer needed for production code. Precise ordering is guaranteed within one observer, but code should not rely on the relative order of callbacks between different observers watching the same changes.

Explained without jargon

A web page is built from a tree of pieces, such as headings, buttons and paragraphs. Many things change that tree while the page is open: the site’s own code, advertisements, chat widgets or the visitor. MutationObserver is a built-in watcher that a developer can point at part of the page.

Suppose something in that area changes. The browser waits until the current burst of work is done. Then it hands the watcher a short report of everything that changed. It works like a doorbell camera that sends one summary clip, not an alert for every movement. The page stays fast, and the code still learns exactly what happened.

A typical use case

An online retailer embeds a third-party support chat widget that loads at an unpredictable moment and injects its launcher button into the page. The accessibility team needs every launcher to carry a clear aria-label and to respect the site’s reduced-motion setting, but it cannot change the vendor’s code.

A developer attaches a MutationObserver to the container where the widget mounts, with childList and subtree enabled. When the callback finds an added element matching the launcher selector, it sets the label, removes the animation class and then calls disconnect(). Because the callback runs as a microtask before the next paint, visitors never see the unlabeled version, and the observer stops after its single job, adding no measurable ongoing cost to page performance.