MutationObserver in JavaScript

MutationObserver in JavaScript

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

const observer = new MutationObserver(callback); observer.observe(targetNode, config);
  • 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

const target = document.getElementById("content"); const observer = new MutationObserver((mutations) => { mutations.forEach((mutation) => { if (mutation.type === "childList") { console.log("Child nodes changed!", mutation); } }); }); observer.observe(target, { childList: true });

Detects when child elements are added or removed.

3️⃣ Observing Attribute Changes

Example: Detect changes to attributes

const box = document.getElementById("box"); const observer = new MutationObserver((mutations) => { mutations.forEach((mutation) => { if (mutation.type === "attributes") { console.log(`Attribute "${mutation.attributeName}" changed.`); } }); }); observer.observe(box, { attributes: true });

Detects changes in attributes like class, style, etc.

4️⃣ Observing Text Content Changes

Example: Detect text changes inside an element

const textNode = document.getElementById("message"); const observer = new MutationObserver((mutations) => { mutations.forEach((mutation) => { if (mutation.type === "characterData") { console.log("Text content changed:", mutation.target.nodeValue); } }); }); observer.observe(textNode, { characterData: true, subtree: true });

Detects changes inside a text node.

5️⃣ Stopping the Observer

You can stop observing changes using disconnect().

observer.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.

Would you like me to help implement a specific use case? 

Soeng Souy

Soeng Souy

Website that learns and reads, PHP, Framework Laravel, How to and download Admin template sample source code free.

Post a Comment

CAN FEEDBACK
close