MutationObserver in JavaScript
The MutationObserver API allows you to watch for changes in the DOM (Document Object Model). It is useful for tracking changes in elements, attributes, or child nodes without using inefficient polling methods like setInterval
.
1️⃣ Basic Syntax
callback
→ Function that runs when mutations occur.targetNode
→ The DOM element to observe.config
→ An object defining what to monitor.
2️⃣ Observing Child Element Changes
Example: Detect when new elements are added
✅ Detects when child elements are added or removed.
3️⃣ Observing Attribute Changes
Example: Detect changes to attributes
✅ Detects changes in attributes like class
, style
, etc.
4️⃣ Observing Text Content Changes
Example: Detect text changes inside an element
✅ Detects changes inside a text node.
5️⃣ Stopping the Observer
You can stop observing changes using disconnect()
.
🚀 Use this when you no longer need to track changes.
6️⃣ Practical Use Cases
✔ Track live updates (e.g., chat messages, notifications).
✔ Detect form changes dynamically.
✔ Watch for UI updates without polling.
✔ Enhance accessibility by reacting to DOM modifications.