MutationObserver, keep an eye for DOM changes ๐Ÿง

MutationObserver lets a script watch the DOM for added, removed or changed nodes, which helps when other scripts on the page rewrite the markup you rely on.

Published ยท Revised ยท 82 words ยท View as Markdown


Javascript has a cool interface to watch for dom changes, MutationObserver. It accepts a callback as a first parameter that gives us access to a mutation list.

const observer = new MutationObserver(function (mutationList, observer) {
    for (const mutation of mutationList) {
      //
    }
});

Mutations have some cool attributes like addedNodes, removedNodes and target

observer.observe(document.querySelector('body'), { childList: true, subtree: true });

Image a scenario where you only control a specific script on a page and that rest of the dom is manipulated by other scripts, mutation observers can come in handy to identify when a node is removed or added. Moreover it is pretty well supported