Mutation Observer
In one line
A Mutation Observer watches a DOM subtree and reports when nodes are added, removed, or attributes change.
In simple words
The Mutation Observer API watches a DOM element (and optionally its descendants) and fires a callback when the tree changes — child nodes added or removed, attributes modified, or text content changed. It is the modern replacement for the deprecated Mutation Events.
Unlike scroll or resize listeners that fire synchronously and frequently, mutation observers deliver changes in batches asynchronously (after the current microtask), so they do not block the main thread even if many mutations happen at once. You configure which mutation types to watch via an options object.
Use cases: framework integration (detect when third-party code injects content), building live extensions that react to page changes, syncing a copy of part of the DOM, and implementing undo/redo for contenteditable elements. It is essential for tools that must observe a DOM they do not control.
Example
const target = document.querySelector("#list");
const observer = new MutationObserver((mutations) => {
mutations.forEach(m => {
m.addedNodes.forEach(node => console.log("Added:", node));
});
});
observer.observe(target, { childList: true });
// Later: target.appendChild(newItem) → logs "Added: <li>"The observer watches childList changes on #list. When a child is appended, the callback fires with the added node.
Related terms
Related Resources
Related Lessons
- Observers
Learn Mutation Observer.
Decode error messages
Plain-English explanations of common errors — what they mean, why they happen, and how to fix them.