DOM updates can arrive from fetch responses, third-party widgets, and component renders long after the initial HTML has loaded. MutationObserver lets browser JavaScript watch a specific part of the DOM and react only when matching child, attribute, or text changes occur.

A focused observer starts with one target node and a small options object. Its callback receives MutationRecord entries in batches after matching changes occur, rather than running immediately inside each DOM operation.

Watching one container and a filtered attribute avoids reacting to unrelated page updates. A log outside the watched container can display changes without triggering the observer itself, while disconnect() stops notifications once the needed state is reached.

Steps to watch DOM changes with MutationObserver:

  1. Create a file named index.html in your text editor with the activity feed and its controls.
    index.html
    <!doctype html>
    <html lang="en">
    <head>
      <meta charset="utf-8">
      <meta name="viewport" content="width=device-width, initial-scale=1">
      <title>Watch DOM changes</title>
      <script src="observer.js" defer></script>
    </head>
    <body>
      <h1>Activity feed</h1>
      <section id="activity-feed" data-state="idle" aria-live="polite">
        <p>No updates yet.</p>
      </section>
      <button type="button" id="add-update">Add update</button>
      <button type="button" id="after-disconnect">Change after disconnect</button>
      <h2>Mutation log</h2>
      <pre id="mutation-output">No mutation records yet.</pre>
    </body>
    </html>

    The defer attribute runs the script after the HTML has been parsed, so the elements exist when JavaScript selects them.
    Related: How to load JavaScript with defer

  2. Create observer.js beside index.html with references to both elements.
    observer.js
    const feed = document.querySelector("#activity-feed");
    const output = document.querySelector("#mutation-output");
  3. Append the observer callback at the end of observer.js.
    observer.js
    const observer = new MutationObserver((mutations) => {
      for (const mutation of mutations) {
        if (mutation.type === "childList") {
          output.textContent += `childList: ${mutation.addedNodes.length} node added\n`;
        } else if (mutation.type === "attributes") {
          output.textContent += `${mutation.attributeName}: ${mutation.oldValue} -> ${feed.dataset.state}\n`;
        }
      }
     
      if (feed.dataset.state === "ready") {
        observer.disconnect();
      }
    });

    addedNodes.length counts inserted nodes, and oldValue holds the previous attribute value when requested. Reading feed.dataset.state gives the current value at callback time, which may include several changes if more than one occurred before delivery. The callback processes the delivered records before disconnecting at ready.

  4. Append the observation options at the end of observer.js.
    observer.js
    observer.observe(feed, {
      childList: true,
      attributes: true,
      attributeFilter: ["data-state"],
      attributeOldValue: true
    });
    output.textContent = "";

    childList watches direct child additions and removals. attributes with attributeFilter limits attribute records to data-state, and attributeOldValue preserves its previous value. At least one of childList, attributes, or characterData must be enabled. The optional subtree: true extends observation to descendants; it is unnecessary for changes directly on feed.

  5. Append the two button handlers at the end of observer.js.
    observer.js
    document.querySelector("#add-update").addEventListener("click", () => {
      const item = document.createElement("p");
      item.textContent = "Profile data loaded.";
      feed.append(item);
      feed.dataset.state = "ready";
    });
     
    document.querySelector("#after-disconnect").addEventListener("click", () => {
      const item = document.createElement("p");
      item.textContent = "This change happens after disconnect.";
      feed.append(item);
      feed.dataset.state = "ignored";
    });

    The first handler appends a paragraph and changes the filtered attribute. The second handler performs another DOM update so the stopped observer's behavior is visible.

  6. Save observer.js with the four JavaScript sections in the order shown.
  7. Open index.html in your browser.
  8. Click Add update once.
  9. Click Change after disconnect after the two mutation lines appear.
  10. Verify that the feed contains both new paragraphs while the mutation log still contains only the original two lines.

    Profile data loaded. and This change happens after disconnect. confirm that both buttons changed the DOM. The log remains childList: 1 node added and data-state: idle → ready because the observer disconnected after the first update. A fresh page load starts observation again.

Share this guide