SyntaxStudy
Sign Up
HTML MutationObserver API
HTML Advanced 4 min read

MutationObserver API

MutationObserver

MutationObserver watches for DOM changes: child additions/removals, attribute changes, and text content changes.

Example
const target = document.getElementById("dynamic-list");

const observer = new MutationObserver(mutations => {
  mutations.forEach(m => {
    if (m.type === "childList") {
      console.log(`${m.addedNodes.length} nodes added`);
    }
    if (m.type === "attributes") {
      console.log(`Attribute ${m.attributeName} changed`);
    }
  });
});

observer.observe(target, {
  childList: true,
  attributes: true,
  subtree: true
});
Pro Tip

Call observer.disconnect() when you no longer need to observe — it prevents memory leaks.