brewedbits.dev

Personal blog with guides and news on selfhosting, Linux and AI, from the Netherlands

nextDash nextdash --aboutYour bookmarks. Your terminal. checks your links knows your Docker host one container, no cloudLive demo →nextdash.cc ↗

Tip: MutationObserver runs your code when other scripts change the page

Javascript
~/tips/tip-js-mutationobserver-watch-dom

const observer = new MutationObserver((mutations) => {

Detect added, removed or changed elements without polling the DOM.

Sometimes a third party widget or a framework adds elements I need to adjust, and there is no event for that. MutationObserver calls me back whenever the DOM under an element changes.

const list = document.querySelector("#comments");

const observer = new MutationObserver((mutations) => {
  for (const m of mutations) {
    for (const node of m.addedNodes) {
      if (node.nodeType === Node.ELEMENT_NODE) {
        node.querySelectorAll("a").forEach((a) => (a.rel = "nofollow"));
      }
    }
  }
});

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

The options decide what to watch. childList reports added and removed children, subtree extends that to all descendants, attributes reports attribute changes (narrow it with attributeFilter), and characterData reports text edits. Each record says what kind of change happened and which nodes were involved.

The callback does not run in the middle of a change. Changes are collected and delivered together shortly after, as a microtask, so a script that adds fifty comments in a loop gives you one call with fifty records.

Two cautions. Watching a large subtree with attributes on can produce a lot of records, so keep the target and the options as narrow as you can. And if your callback changes the same DOM it watches, it triggers itself; guard against that or call disconnect() while you make the change. When you only need to know when an element becomes visible, IntersectionObserver is the better tool.

Further reading: MDN: MutationObserver, MDN: MutationObserver.observe()

More Javascript tips node --inspect-brk app.js obj?.prop const filePath = String.raw`C:\Development\profile\about.html`; const observer = new ResizeObserver((entries) => { URL.parse("not a url"); // null All Javascript tips (40) All topics

Link