Back to APIs

MutationObserver

Observers

Provides the ability to watch for changes being made to the DOM tree.

Support99%
BaselineWidely available
ImpactHigh
Popularity🔥 85

When to Use

  • Monitoring a third-party widget for inserted nodes.
  • Implementing custom polyfills or custom elements.
  • Tracking text changes inside contenteditable elements.

When NOT to Use

  • When React or Vue state could just be used instead.
  • When you just need to know if an element entered the viewport (use IntersectionObserver).

Code Examples

Good: Observing a specific container

Observes only the specific container and disconnects later.

const target = document.getElementById('my-list');
const observer = new MutationObserver((mutationsList) => {
  for (const mutation of mutationsList) {
    if (mutation.type === 'childList') {
      console.log('A child node has been added or removed.');
    }
  }
});
observer.observe(target, { childList: true });

Advantages

  • Batched asynchronous updates (does not block the main thread like legacy MutationEvents).
  • Configurable to watch attributes, text content, or child lists.

Limitations

  • Can cause infinite loops if the observer callback mutates the observed DOM.
  • Heavy memory overhead if observing document.body with `subtree: true`.

Common Mistakes

  • Leaving observers running after component unmount.
  • Observing the entire document subtree without filtering.

References