Codectionary / Developer documentation / JavaScript

MutationObserver

MutationObserver watches for changes to the DOM tree - added/removed elements, attribute changes, or text content changes - and runs a callback in response. It is useful for reacting to DOM changes made by other scripts or third-party widgets that you do not directly control.

Syntax

new MutationObserver(callback).observe(target, options)

Examples

Watching for Added Child Elements

Reacting whenever new elements are added to a container.

const container = document.querySelector("#chatMessages");

const observer = new MutationObserver((mutations) => {
  mutations.forEach(mutation => {
    if (mutation.addedNodes.length > 0) {
      console.log("New message added, scrolling to bottom");
      container.scrollTop = container.scrollHeight;
    }
  });
});

observer.observe(container, { childList: true });

Watching for Attribute Changes

Reacting when a specific attribute changes on an element.

const target = document.querySelector("#statusBadge");

const observer = new MutationObserver((mutations) => {
  mutations.forEach(mutation => {
    if (mutation.attributeName === "class") {
      console.log("Class changed to:", target.className);
    }
  });
});

observer.observe(target, { attributes: true });

// Stop watching when no longer needed
// observer.disconnect();

Best practices

  • Use MutationObserver only when you genuinely need to react to DOM changes you do not control directly - if you control the code making the change, call your reaction logic directly instead
  • Always call disconnect() when done observing, to avoid unnecessary background processing
  • Be specific with the options object (childList, attributes, subtree) rather than observing everything, for better performance
  • Avoid triggering more DOM mutations synchronously inside the callback in a way that could create an infinite mutation loop

At a glance

Purpose
Application logic and interaction
File extension
.js ยท .mjs
Runs in
Browsers and JavaScript runtimes
Usually used with
HTML, CSS and Web APIs

Specifications & further reading

Related JavaScript documentation