0
0
JavascriptHow-ToBeginner · 3 min read

How to Use Mutation Observer in JavaScript: Syntax and Example

Use MutationObserver in JavaScript by creating an observer with a callback function, then call observe() on a target node with options specifying which DOM changes to watch. This lets you react to changes like added or removed elements, attribute changes, or text updates.
📐

Syntax

The MutationObserver is created by passing a callback function that runs when mutations occur. You then call observe() on the observer, giving it the target node and an options object to specify what changes to watch.

  • callback: Function called with mutation records.
  • targetNode: The DOM node to watch.
  • options: Object specifying mutation types to observe.
javascript
const observer = new MutationObserver(callback);

observer.observe(targetNode, {
  childList: true,      // watch for added or removed child nodes
  attributes: true,     // watch for attribute changes
  subtree: true,        // watch all descendants
  characterData: true   // watch text changes
});
💻

Example

This example watches a div for added child elements and logs a message when a new child is added.

javascript
const targetNode = document.getElementById('myDiv');

const observer = new MutationObserver((mutationsList) => {
  for (const mutation of mutationsList) {
    if (mutation.type === 'childList' && mutation.addedNodes.length > 0) {
      console.log('A child node has been added.');
    }
  }
});

observer.observe(targetNode, { childList: true });

// To test, add a new element after 2 seconds
setTimeout(() => {
  const newElement = document.createElement('p');
  newElement.textContent = 'Hello!';
  targetNode.appendChild(newElement);
}, 2000);
Output
A child node has been added.
⚠️

Common Pitfalls

  • Not disconnecting the observer when no longer needed can cause memory leaks.
  • Forgetting to specify the correct options means no mutations will be observed.
  • Observing large subtrees without filtering can cause performance issues.
  • Assuming mutations are synchronous; the callback runs asynchronously after changes.
javascript
/* Wrong: No options passed, so no mutations detected */
const observer = new MutationObserver(() => {
  console.log('Mutation detected');
});
observer.observe(document.body, {}); // Missing options object

/* Right: Specify options to watch childList changes */
observer.observe(document.body, { childList: true, subtree: true });
📊

Quick Reference

OptionDescription
childListWatch for added or removed child nodes
attributesWatch for attribute changes on the target node
characterDataWatch for changes to the text content of the node
subtreeWatch all descendants of the target node
attributeOldValueRecord previous attribute value
characterDataOldValueRecord previous text content

Key Takeaways

Create a MutationObserver with a callback to react to DOM changes.
Call observe() on the target node with options to specify what to watch.
Always disconnect the observer when done to avoid memory leaks.
Specify options carefully; no options means no mutations detected.
MutationObserver callbacks run asynchronously after changes happen.