Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / JavaScript

MutationObserver: observe(), disconnect(), and takeRecords()

Watch selected DOM changes, collect pending records without waiting for the callback, and stop observing with or without keeping the records still in the queue.

Version: ECMAScript 2024 and the current web platform; runtime support varies

Syntax

const observer = new MutationObserver(callback);
observer.observe(target, options);
const records = observer.takeRecords();
observer.disconnect();

MutationObserver.observe/disconnect/takeRecords names three instance methods, not static methods. new MutationObserver(callback) creates the observer but does not start it. Matching changes are queued, and a notification microtask passes a batch to callback(records, observer) instead of calling it synchronously for each change.

observe(target, options) registers a DOM Node and returns undefined. Further calls can add different targets or update the options for the same target. childList watches additions and removals of direct children, attributes watches attribute changes, and characterData watches changes to a node's data, such as the contents of a text node. subtree: true applies the same rules to descendants. Changes in a removed branch can still be queued before the next notification microtask.

attributeFilter limits which attribute names are watched. attributeOldValue: true and characterDataOldValue: true save the previous value in oldValue. If attributes is omitted, providing attributeFilter or attributeOldValue enables attribute observation; providing characterDataOldValue similarly enables characterData if omitted. observe() throws TypeError if no change type is enabled, if attributes: false is combined with a filter or attributeOldValue: true, or if characterData: false is combined with characterDataOldValue: true.

takeRecords() synchronously returns an array of pending MutationRecord objects ([] if none) and empties the queue. It neither stops observation nor calls the callback; you handle the returned records yourself. disconnect() returns undefined, stops observation of all targets for that instance, and discards undelivered records. To keep them, call takeRecords() immediately before disconnect(). Call observe() again to reuse the observer.

This is a web-platform DOM API, not part of ECMAScript 2024. Availability depends on the runtime. The observer does not grant access to nodes you cannot otherwise access, such as those inside a cross-origin iframe.

Examples

<!doctype html>
<meta charset="utf-8">
<title>MutationObserver example</title>
<script>
  const target = document.createElement('div');
  const options = { attributes: true, attributeFilter: ['data-state'] };
  const observer = new MutationObserver((records, currentObserver) => {
    console.log(`callback: ${records.length} ${records[0].attributeName}`);
    currentObserver.disconnect();
  });

  observer.observe(target, options);
  target.setAttribute('data-state', 'first');
  const [record] = observer.takeRecords();
  console.log(`taken: ${record.type} ${record.attributeName}`);

  target.setAttribute('data-state', 'discarded');
  observer.disconnect();
  target.setAttribute('data-state', 'unobserved');
  console.log(`remaining: ${observer.takeRecords().length}`);

  observer.observe(target, options);
  target.setAttribute('data-state', 'delivered');
</script>

Result

taken: attributes data-state
remaining: 0
callback: 1 data-state

Save the complete example as an HTML file, open it in a browser, and check the developer console. The element is not attached to the page. `takeRecords()` collects the first record, `disconnect()` discards the second, and the change while disconnected is not recorded. Only the change after observation resumes reaches the callback.

Related lessons

  • JavaScript · Lesson 31 · Intermediate · Version: 3

Sources