← Back to JavaScript, page 8

javascript-0148 · Medium mid

How does MutationObserver work, what can it observe, and what are the common pitfalls?

MutationObserver watches a DOM node for changes to child nodes, attributes, or text, and calls your callback with a batch of records after the current script finishes, as a microtask. You configure what to watch with options such as childList, attributes, characterData, and subtree. Disconnect it when finished and avoid changing the observed node inside the callback in a way that triggers it again.

Full answer

A MutationObserver is the modern replacement for the old mutation events. It reports DOM changes efficiently, in batches, and asynchronously.

Setup: const observer = new MutationObserver(callback) and then observer.observe(target, options). The options choose what to watch, and at least one of childList, attributes, or characterData must be true:

  • childList: nodes added to or removed from the target.
  • attributes: attribute changes, with attributeFilter to limit the names and attributeOldValue to keep the previous value.
  • characterData: changes to the text of text nodes.
  • subtree: also watch all descendants, not only the target itself.

Callback: it receives an array of MutationRecord objects and the observer. Each record has type (childList, attributes, or characterData), target, addedNodes, removedNodes, attributeName, and oldValue. Records are queued while code runs, and the callback is called once, as a microtask, after the current script finishes. So ten changes in one function produce one callback with ten records. observer.takeRecords() empties the queue immediately, and disconnect() stops observing.

Use cases: reacting to content inserted by third-party scripts or widgets, waiting for an element to appear, undo history for editors, syncing attribute changes, and testing.

Pitfalls:

  • Infinite loops: if the callback changes the observed node (for example, rewrites an attribute), it triggers new records. Disconnect before changing, or guard with checks.
  • Performance: observing a large subtree with attributes and character data on a page that changes constantly produces many records. Observe the smallest node and the smallest set of options.
  • Changes to properties that are not attributes (such as input.value) are not reported.
  • It does not report layout or style changes, only DOM tree changes. Use ResizeObserver and IntersectionObserver for other things.
  • Forgetting disconnect() on removed components keeps the callback and the nodes alive.

If you control the code that changes the DOM, call your own function or dispatch a custom event rather than observing from far away. The observer is best for changes you do not control.

javascript
document.body.innerHTML = '<ul id="list"><li>one</li></ul><p id="note" data-state="idle">hello</p>';
const list = document.getElementById('list');
const note = document.getElementById('note');
const batches = [];

const observer = new MutationObserver((records) => {
  batches.push(
    records.map((record) => {
      if (record.type === 'childList') return `childList: +${record.addedNodes.length} -${record.removedNodes.length}`;
      if (record.type === 'attributes') return `attribute ${record.attributeName}: ${record.oldValue} -> ${record.target.getAttribute(record.attributeName)}`;
      return `characterData: ${record.oldValue} -> ${record.target.data}`;
    }),
  );
});
observer.observe(list, { childList: true });
observer.observe(note, { attributes: true, attributeFilter: ['data-state'], attributeOldValue: true, characterData: true, characterDataOldValue: true, subtree: true });

// several changes in one script produce one callback with several records
const item = document.createElement('li');
item.textContent = 'two';
list.append(item);
list.firstElementChild.remove();
note.setAttribute('data-state', 'busy');
note.setAttribute('class', 'ignored by the attribute filter');
note.firstChild.data = 'hello world';
console.log('callbacks so far (synchronous code):', batches.length);

Promise.resolve().then(() => {
  console.log('after one microtask:', batches.length, 'callback(s)');
  console.log(batches[0]);

  // takeRecords empties the queue and returns the pending records at once
  note.setAttribute('data-state', 'done');
  const pending = observer.takeRecords();
  console.log('takeRecords returned:', pending.length, 'record(s) of type', pending[0].type);
}).then(() => {
  console.log('callback was not called for records that were taken:', batches.length);

  // a callback that changes what it observes can loop: guard it
  let calls = 0;
  const guarded = new MutationObserver(() => {
    calls++;
    guarded.disconnect(); // stop before changing the observed node
    note.setAttribute('data-count', String(calls));
    guarded.observe(note, { attributes: true, attributeFilter: ['data-state'] });
  });
  guarded.observe(note, { attributes: true, attributeFilter: ['data-state'] });
  note.setAttribute('data-state', 'again');
  return new Promise((resolve) => setTimeout(() => {
    console.log('guarded callback ran', calls, 'time(s); data-count =', note.getAttribute('data-count'));
    guarded.disconnect();
    observer.disconnect();
    resolve();
  }, 5));
}).then(() => {
  const input = document.createElement('input');
  document.body.append(input);
  const valueObserver = new MutationObserver((records) => console.log('input records:', records.length));
  valueObserver.observe(input, { attributes: true });
  input.value = 'typed text';
  input.setAttribute('placeholder', 'name');
  return Promise.resolve().then(() => valueObserver.disconnect());
});

Written for a browser console or script tag; checked here with Node.js v24.22.1 and jsdom, two runs with identical output. Output: callbacks so far (synchronous code): 0 after one microtask: 1 callback(s) [ 'childList: +1 -0', 'childList: +0 -1', 'attribute data-state: idle -> busy', 'characterData: hello -> hello world' ] takeRecords returned: 1 record(s) of type attributes callback was not called for records that were taken: 1 guarded callback ran 1 time(s); data-count = 1 input records: 1

Key points

  • It watches childList, attributes, and characterData, optionally for the whole subtree.
  • Records are batched and delivered once as a microtask after the current script.
  • Use attributeFilter and attributeOldValue; takeRecords empties the queue; disconnect stops it.
  • Pitfalls: loops when the callback changes the observed node, broad observation cost, input.value is not reported.
  • Best for changes you do not control; for your own changes use direct calls or custom events.

Common mistakes

  • Changing the observed node in the callback without a guard, causing an endless loop.
  • Observing the whole document body with every option on a busy page.
  • Expecting input.value or other property changes to be reported.
  • Forgetting to disconnect when a component is destroyed.

Follow-ups

  • Why are mutation events deprecated, and how does MutationObserver improve on them?
  • How would you wait for an element to appear in the page?
  • What is the difference between MutationObserver, ResizeObserver, and IntersectionObserver?

Tips

  • Say that records are batched and delivered as a microtask.
  • List the options and one pitfall for each.
  • Prefer direct calls or custom events when you control the change.