MutationObserver

Published by Brayan K

MutationObserver is a browser API that watches a part of the DOM and calls you back with a list of exactly what changed — nodes added or removed, attributes edited, or text rewritten.

Part of the free JavaScript course at LearnCodingFast — hands-on lessons with examples you run in your browser, plus practice exercises and a quick quiz.

Observe selected DOM mutations, then inspect the delivered batch

MutationObserver watches the mutation types and subtree you request. It does not report every JavaScript property change, computed style change or rendered pixel. The introduction’s “exactly what changed” means mutation records, not immutable before-and-after snapshots of the entire DOM.

const target = document.createElement("div");
document.getElementById("app").append(target);
let finish;
const delivered = new Promise(resolve => { finish = resolve; });
// Ask for previous attribute values explicitly.
const observer = new window.MutationObserver(records => finish(records));
observer.observe(target, { attributes: true, attributeOldValue: true });
target.setAttribute("data-state", "loading");
target.setAttribute("data-state", "ready");
const records = await delivered;
console.log(records.length);
console.log(JSON.stringify(records.map(record => ({
  type: record.type, name: record.attributeName, old: record.oldValue,
  current: record.target.getAttribute(record.attributeName)
}))));
observer.disconnect();
target.remove();

// ✅ Expected output:
// 2
// [{"type":"attributes","name":"data-state","old":null,"current":"ready"},{"type":"attributes","name":"data-state","old":"loading","current":"ready"}]

The records preserve the requested old values. Reading the target during delivery sees its current state, which may already include later edits. There is no newValue field that freezes each intermediate attribute value. Decide whether you need a record audit or simply to recompute the current derived state.

Child-list changes and text-node edits are different mutations

const root = document.createElement("div");
const text = document.createTextNode("old");
root.append(text);
const observer = new window.MutationObserver(() => {});
observer.observe(root, { childList: true, characterData: true, characterDataOldValue: true, subtree: true });
text.data = "edited";
const first = observer.takeRecords();
root.textContent = "replacement";
const second = observer.takeRecords();
console.log(first[0].type, first[0].oldValue);
console.log(second[0].type, second[0].addedNodes.length, second[0].removedNodes.length);
observer.disconnect();

// ✅ Expected output:
// characterData old
// childList 1 1

characterData observes changes to the data of an existing text node. Setting an element’s textContent can replace its children, producing childList records. subtree extends the selected mutation types to descendants; observing a parent without subtree does not automatically observe attributes of all its children. DOM Manipulation owns nodes and text updates.

const root = document.createElement("div"), child = document.createElement("span");
root.append(child);
const observer = new window.MutationObserver(() => {});
observer.observe(root, { attributes: true });
child.setAttribute("data-state", "first");
console.log(observer.takeRecords().length);
observer.observe(root, { attributes: true, subtree: true });
child.setAttribute("data-state", "second");
console.log(observer.takeRecords().length);
observer.disconnect();

// ✅ Expected output:
// 0
// 1

Filter for the actual state boundary you own

const root = document.createElement("div");
const observer = new window.MutationObserver(() => {});
observer.observe(root, { attributes: true, attributeFilter: ["data-state"] });
root.setAttribute("title", "ignored");
root.setAttribute("data-state", "ready");
console.log(observer.takeRecords().map(record => record.attributeName).join(", "));
observer.disconnect();

// ✅ Expected output:
// data-state
const input = document.createElement("input");
const observer = new window.MutationObserver(() => {});
observer.observe(input, { attributes: true });
input.value = "typed value";
console.log(observer.takeRecords().length);
input.setAttribute("value", "default value");
console.log(observer.takeRecords().length, input.value);
observer.disconnect();

// ✅ Expected output:
// 0
// 1 typed value

The live input value and its value attribute are distinct. Observe input/change events when the requirement concerns user edits; a mutation observer is not a replacement for an event listener. Events owns those interactions. For geometry or visibility changes, IntersectionObserver (Lazy Load & Infinite Scroll) owns intersection observation.

const observer = new window.MutationObserver(() => {});
observer.observe(document.createElement("div"), {});

// ✅ Expected error:
// TypeError: Failed to execute 'observe' on 'MutationObserver': The options object must set at least one of 'attributes', 'characterData', or 'childList' to true.

Options have consistency rules. Asking for attributeOldValue or attributeFilter can imply attributes when it is omitted, but explicitly setting attributes false with those options is invalid. State the desired categories explicitly in application code so the observed boundary is easy to review.

Draining or disconnecting changes what will be delivered

const root = document.createElement("div");
let calls = 0;
const observer = new window.MutationObserver(() => calls++);
observer.observe(root, { attributes: true });
root.setAttribute("data-state", "ready");
console.log(observer.takeRecords().length);
await Promise.resolve();
console.log(calls, observer.takeRecords().length);
observer.disconnect();

// ✅ Expected output:
// 1
// 0 0
const root = document.createElement("div");
let calls = 0;
const observer = new window.MutationObserver(() => calls++);
observer.observe(root, { childList: true });
root.append(document.createElement("span"));
observer.disconnect();
await Promise.resolve();
console.log(calls, observer.takeRecords().length);

// ✅ Expected output:
// 0 0

If pending records are important, drain and process them before disconnecting. If disposal means “discard unfinished updates,” disconnecting without a final flush is a deliberate policy. Neither takeRecords nor disconnect changes the DOM.

An observer callback that mutates its own observed state can queue more records and create a feedback loop. Compare the derived result before publishing, filter irrelevant attributes and keep rendered status outside the observed subtree when possible. Scheduling every mutation into another microtask does not by itself eliminate a logical cycle.

Guided exercise: request only the attribute history you need

Fill the literal hints to observe one named attribute and retain its old value. Draining the queue lets this small exercise inspect the records directly.

const root = document.createElement("div");
root.setAttribute("data-state", "idle");
const observer = new window.MutationObserver(() => {});
observer.observe(root, {
  attributes: true,
  attributeFilter: ["___"], // 👉 replace ___ with data-state
  attributeOldValue: ___ // 👉 replace ___ with true
});
root.setAttribute("data-state", "ready");
console.log(observer.___()[0].oldValue); // 👉 replace ___ with takeRecords
observer.disconnect();

// ✅ Expected output:
// idle

Brief: publish only changed checklist counts

Implement watchChecklist(root) for an HTMLElement. Count descendants carrying data-item; the root itself is excluded. A counted item is done only when data-done is exactly the string true. Compute an initial frozen snapshot immediately, then observe subtree child changes and only data-item/data-done attribute changes.

After a delivered batch, recompute current counts once. If total and done are unchanged, publish nothing. Otherwise dispatch a non-bubbling checklist-counts CustomEvent on the root with a frozen detail record. read() returns a fresh frozen copy of the last published snapshot. The observer itself must not rewrite the observed DOM.

dispose is terminal and idempotent. It discards pending updates, stops observation and preserves the last published snapshot. Consumers that mutate the list in response to events remain responsible for avoiding their own cycles. This derives counts from ordinary DOM state; it is not an audit log of every intermediate mutation.

function watchChecklist(root) {
  if (!(root instanceof HTMLElement)) throw new TypeError("root must be an HTMLElement");
  function measure() {
    const items = [...root.querySelectorAll("[data-item]")];
    return { total: items.length, done: items.filter(item => item.getAttribute("data-done") === "true").length };
  }
  let active = true;
  let current = Object.freeze(measure());
  const observer = new window.MutationObserver(() => {
    if (!active) return;
    const next = measure();
    if (next.total === current.total && next.done === current.done) return;
    current = Object.freeze(next);
    root.dispatchEvent(new CustomEvent("checklist-counts", { detail: current }));
  });
  observer.observe(root, {
    childList: true, subtree: true, attributes: true,
    attributeFilter: ["data-item", "data-done"]
  });
  return Object.freeze({
    read() { return Object.freeze({ ...current }); },
    dispose() {
      if (!active) return;
      active = false;
      observer.disconnect();
    }
  });
}
const root = document.createElement("ul");
document.getElementById("app").append(root);
const reports = [];
root.addEventListener("checklist-counts", event => reports.push(event.detail));
const tracking = watchChecklist(root);
const first = document.createElement("li"), second = document.createElement("li");
first.setAttribute("data-item", "");
second.setAttribute("data-item", "");
root.append(first, second);
first.setAttribute("data-done", "true");
await Promise.resolve();
console.log(JSON.stringify(tracking.read()), reports.length, Object.isFrozen(reports[0]));
second.setAttribute("title", "not counted");
await Promise.resolve();
console.log(reports.length);
const before = tracking.read();
tracking.dispose();
second.setAttribute("data-done", "true");
await Promise.resolve();
console.log(JSON.stringify(tracking.read()), before === tracking.read());
root.remove();

// ✅ Expected output:
// {"total":2,"done":1} 1 true
// 1
// {"total":2,"done":1} false

Practice quiz

What does this complete program print? const root=document.createElement("div");const observer=new window.MutationObserver(()=>{});observer.observe(root,{attributes:true});root.setAttribute("data-x","1");console.log(observer.takeRecords()[0].type);observer.disconnect();

  • attributes
  • childList
  • characterData
  • change

Answer: attributes. An attribute write produces an attributes record.

What does reading record.target during callback delivery observe?

  • An immutable copy from the moment of the mutation
  • The target’s current state
  • Only the first mutation’s new value
  • A detached JSON snapshot

Answer: The target’s current state. The target is a live node reference; later changes may already be present.

What does this complete program print? const root=document.createElement("div");const observer=new window.MutationObserver(()=>{});observer.observe(root,{childList:true});root.append(document.createElement("span"));console.log(observer.takeRecords().length,observer.takeRecords().length);observer.disconnect();

  • 1 1
  • 0 0
  • 1 0
  • 0 1

Answer: 1 0. The first drain consumes the queued record.

Which option extends observation to descendants?

  • deep
  • children
  • recursive
  • subtree

Answer: subtree. subtree applies the selected mutation categories to descendants.

What does this complete program print? const input=document.createElement("input");const observer=new window.MutationObserver(()=>{});observer.observe(input,{attributes:true});input.value="x";console.log(observer.takeRecords().length);observer.disconnect();

  • 0
  • 1
  • 2
  • TypeError

Answer: 0. Setting the live value property does not mutate the value attribute here.

How can a derived-count observer avoid needless repeated notifications?

  • Publish once for every record regardless of result
  • Compare the new counts with its last published counts
  • Write the same observed attribute in every callback
  • Watch the whole document without filters

Answer: Compare the new counts with its last published counts. Only publishing a changed derived result avoids redundant notifications.

What does this complete program print? const root=document.createElement("div");const observer=new window.MutationObserver(()=>{});observer.observe(root,{attributes:true});root.setAttribute("data-x","1");observer.disconnect();console.log(observer.takeRecords().length);

  • 1
  • undefined
  • 0
  • TypeError

Answer: 0. Disconnect discards undelivered records.

Which mechanism should track user edits to an input’s live value?

  • Only attributeOldValue
  • Only childList records
  • Only a polling getAttribute call
  • The appropriate input/change events

Answer: The appropriate input/change events. Mutation records do not replace the input control’s interaction events.

Continue this course

Related lessons