Hiprup

What is MutationObserver?

MutationObserver watches an element for DOM changes — added/removed nodes, attribute changes, or text changes — and runs a callback.

  • Efficient — batches changes and reports them asynchronously, unlike old polling.

  • Configurable — choose what to watch (childList, attributes, subtree).

Useful for reacting to DOM changes you don't control, like third-party widgets or injected content.

const observer = new MutationObserver((mutations) => {
  mutations.forEach(mutation => {
    if (mutation.type === 'childList') {
      console.log('Children changed:', mutation.addedNodes, mutation.removedNodes);
    }
    if (mutation.type === 'attributes') {
      console.log(`Attribute '${mutation.attributeName}' changed`);
    }
  });
});

observer.observe(document.getElementById('app'), {
  childList: true,     // Watch child additions/removals
  attributes: true,    // Watch attribute changes
  subtree: true,       // Watch all descendants
  characterData: true  // Watch text changes
});

observer.disconnect(); // Stop observing

MutationObserver takes a callback that fires with a list of MutationRecord objects. observe() starts watching with configuration (what types of changes to track). subtree: true watches all descendants, not just direct children. disconnect() stops observation and frees resources.

MutationObserver replaces deprecated Mutation Events. It is asynchronous (batches changes, does not fire during DOM modification).

Configuration controls what to watch (children, attributes, text). disconnect() for cleanup.

What is MutationObserver? | Hiprup