Script Valley
JavaScript in the Browser: DOM, Events & APIs
Web APIs: History, URL, Clipboard, and ObserversLesson 6.4

MutationObserver: watching DOM changes without polling

MutationObserver API, observe, disconnect, MutationRecord, childList, attributes, subtree, characterData

MutationObserver

MutationObserver watches a DOM node for changes and fires a callback when mutations occur — without setInterval polling.

const target = document.querySelector('#live-feed');

const observer = new MutationObserver((mutations) => {
  mutations.forEach(mutation => {
    if (mutation.type === 'childList') {
      mutation.addedNodes.forEach(node => {
        console.log('Added:', node.textContent);
      });
    }
  });
});

observer.observe(target, {
  childList: true,   // watch for added/removed children
  subtree: true,     // include all descendants
  attributes: true,  // watch attribute changes
  characterData: true // watch text content changes
});

// Stop observing
observer.disconnect();

Use Cases

MutationObserver is used to detect when third-party scripts modify the DOM, build custom element upgrade logic, track dynamically injected content for analytics, or implement undo/redo by recording DOM state changes.

Always call disconnect() when observation is no longer needed to prevent memory leaks.

Up next

ResizeObserver: reacting to element size changes

Sign in to track progress