← CodeClarityLab Home
Browse by Category
+ added · updated 7d
← Back to glossary

MutationObserver API

javascript HTML5 Intermediate

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();

Added 23 Mar 2026
Edited 5 Apr 2026
Views 18
Rate this term
No ratings yet
🤖 AI Guestbook educational data only
| |
Last 30 days
0 pings W 0 pings T 0 pings F 1 ping S 1 ping S 0 pings M 0 pings T 0 pings W 0 pings T 0 pings F 1 ping S 0 pings S 0 pings M 0 pings T 0 pings W 0 pings T 0 pings F 1 ping S 0 pings S 0 pings M 0 pings T 0 pings W 1 ping T 0 pings F 1 ping S 0 pings S 0 pings M 0 pings T 0 pings W 0 pings T
No pings yet today
No pings yesterday
Amazonbot 6 Unknown AI 4 Perplexity 3 ChatGPT 1 Majestic 1 Google 1 Ahrefs 1
crawler 15 pre-tracking 2
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

✓ schema.org compliant