MediumDOM & Events📖 Theory Question

What is MutationObserver and when do you use it?

💡

Hint

Watch for DOM changes asynchronously — replaces deprecated Mutation Events

Full Answer

MutationObserver watches for changes to the DOM tree and fires a callback when changes occur — batched and asynchronous.

const observer = new MutationObserver((mutations, obs) => {
  mutations.forEach(mutation => {
    if (mutation.type === 'childList') {
      console.log('Added:', mutation.addedNodes);
      console.log('Removed:', mutation.removedNodes);
    }
    if (mutation.type === 'attributes') {
      console.log('Attr changed:', mutation.attributeName, 'on', mutation.target);
    }
    if (mutation.type === 'characterData') {
      console.log('Text changed');
    }
  });
});

observer.observe(document.getElementById('app'), {
  childList: true,     // watch add/remove of child nodes
  attributes: true,    // watch attribute changes
  characterData: true, // watch text content changes
  subtree: true,       // observe all descendants too
});

observer.disconnect(); // stop observing

Use cases: Lazy loading, detecting when third-party code modifies the DOM, building virtual DOM diffing, accessibility announcements.

💡 MutationObserver replaced deprecated synchronous Mutation Events (DOMNodeInserted etc.) which were slow and could cause infinite loops. MutationObserver batches changes for performance.

More DOM & Events Questions

EasyExplain event delegation and why it is useful.EasyWhat is the difference between event.stopPropagation() and event.preventDefault()?EasyWhat is the difference between event bubbling and event capturing?EasyHow do you create and dispatch Custom Events?

Practice this in a timed sprint →

5 free questions, no signup required

⚡ Start Sprint