Concept Explanation
Sometimes you don't control the code that changes the page — a third-party widget, a chat script, or another team's component might inject elements at any moment. How do you react when the DOM changes out from under you?
A MutationObserver is a security camera pointed at a slice of the DOM. Instead of checking "did anything change?" a thousand times a second, you tell the browser: "Watch this element. When a child is added, removed, or an attribute changes, call me."
Syntax or Core Structure
const camera = new MutationObserver((records) => {
records.forEach((record) => {
console.log("Something changed:", record.type);
});
});
camera.observe(document.querySelector("#feed"), {
childList: true, // watch for added/removed children
attributes: true, // watch for attribute changes
subtree: true // watch all descendants too
});
Real World Example
Auto-cleaning the page: A third-party script keeps injecting pop-up banners. You point a MutationObserver at document.body, and every time a node with class .ad appears, your callback instantly removes it — no polling, no lag.
Common Mistakes
- Watching Everything: Setting
subtree: trueondocument.bodyfires constantly on busy pages. Scope your observer to the smallest element possible. - Infinite Loops: If your callback edits the DOM it's watching, it triggers itself again. Call
disconnect()before editing, then re-observe. - Forgetting to Disconnect: Like all observers, call
camera.disconnect()when you're done to free memory.
Best Practices
- Be Specific: Only enable the options you actually need (
childList,attributes,characterData). - Batch the Records: The callback receives an array of changes at once — loop through them instead of expecting one at a time.
Practice Exercises
- The Guard: Watch a
<div>and log a message every time a new child element is added. - The Attribute Spy: Observe a button and log whenever its
disabledattribute flips. - The Self-Healer: If anyone deletes a critical element, use the observer to instantly add it back.