MutationObserver API
TL;DR
MutationObserver watches DOM tree changes — attribute changes, child additions/removals, text content changes — without polling or event listener on each node.
Explanation
MutationObserver fires when the observed DOM subtree changes. Config options: childList (child add/remove), attributes (attribute changes), subtree (observe all descendants), characterData (text changes), attributeFilter (specific attributes). Each callback receives MutationRecord[] with type, target, addedNodes, removedNodes, attributeName, oldValue. Use cases: third-party content monitoring, auto-initializing widgets on dynamic HTML, form auto-save on change. Performance: batches mutations and calls callback asynchronously. Alternative to legacy DOMSubtreeModified event.
Common Misconception
✗ MutationObserver fires synchronously for each change — it batches mutations and fires the callback asynchronously after the current script completes.
Why It Matters
MutationObserver enables reactive patterns for DOM changes without expensive polling loops — essential for progressive enhancement and third-party script integration.
Common Mistakes
- Not disconnecting on cleanup — observes forever.
- Infinite loops: modifying the DOM inside the callback triggers the observer again.
- Observing document.body with subtree:true — very expensive on large pages.
Code Examples
✗ Vulnerable
// Polling instead of observing:
setInterval(() => {
if (document.querySelector('.new-content')) {
initWidget();
}
}, 100);
✓ Fixed
const observer = new MutationObserver(mutations => {
for (const mutation of mutations) {
for (const node of mutation.addedNodes) {
if (node.classList?.contains('widget')) initWidget(node);
}
}
});
observer.observe(document.body, { childList: true, subtree: true });
// Cleanup: observer.disconnect();
Tags
🤝 Adopt this term
£79/year · your link shown here
Added
23 Mar 2026
Edited
5 Apr 2026
Views
18
🤖 AI Guestbook educational data only
|
|
Last 30 days
Agents 0
No pings yet today
No pings yesterday
Amazonbot 6
Unknown AI 4
Perplexity 3
ChatGPT 1
Majestic 1
Google 1
Ahrefs 1
Also referenced
How they use it
crawler 15
pre-tracking 2
Related categories
⚡
DEV INTEL
Tools & Severity
🔵 Info
⚙ Fix effort: Low
⚡ Quick Fix
Replace polling (setInterval + querySelector) with MutationObserver for DOM change detection. Disconnect when no longer needed.
📦 Applies To
javascript HTML5
web
🔗 Prerequisites
🔍 Detection Hints
MutationObserver
Auto-detectable:
✗ No
🤖 AI Agent
Confidence: Low
False Positives: High
✗ Manual fix
Fix: Medium
Context: Function