CodeBlanks Logo Icon CodeBlanks

MutationObserver

JavaScript course · Advanced · Lesson 90/100

Learn to use MutationObserver to watch DOM changes.

MutationObserver

MutationObserver is an API that watches the DOM for changes. It can detect nodes added to or removed from an element, attributes that change, or text content that shifts. Instead of polling with setInterval, the browser notifies you when a change happens, which keeps performance healthy.

You first write a callback, then create the observer with new MutationObserver(callback). The observe method says which element and which change types to watch. When you are done, call disconnect to stop observing.

observe options

You pass an options object as the second argument to observe. The most common ones are:

  • childList: direct child nodes being added or removed
  • attributes: attribute changes
  • subtree: covers the whole descendant tree
  • characterData: text node contents

You can narrow the attributes with attributeFilter. All default to off; turn on the ones you need.

Callback and MutationRecord

The callback takes two arguments: the mutations array and the observer itself. Each MutationRecord describes a single change. Common fields:

  • type: childList, attributes, or characterData
  • target: the element that changed
  • addedNodes and removedNodes: nodes added or removed
  • attributeName: the name of the changed attribute

When several changes arrive together, the array holds multiple records, so loop through them.

Exercise Watch items added to a list

Create a MutationObserver that logs nodes added to the #list element. Turn on the childList option.

Show example solution
1. Create with new MutationObserver((mutations) => {...}).
2. Loop over the mutations array and log addedNodes.
3. Start watching with observer.observe(list, { childList: true }).

Example solution:
const observer = new MutationObserver((mutations) => {
  for (const m of mutations) {
    for (const node of m.addedNodes) {
      console.log(node);
    }
  }
});
observer.observe(list, { childList: true });

Test yourself

  1. Which is a good use case for MutationObserver?

    • Tracking whether a button was clicked
    • Running code when the page loads
    • Noticing items dynamically added to a list
    • Following the user's mouse position
    Show answer

    Noticing items dynamically added to a list — Correct. MutationObserver catches nodes added to or removed from the DOM, like dynamic list updates.

  2. Enable childList watching

    observer.observe(list, {____});
    Show answer
    observer.observe(list, {childList: true});
  3. Match MutationRecord fields

    type
    Change type
    target
    Changed element
    addedNodes
    Added nodes
    attributeName
    Changed attribute

All lessons in Advanced