Skip to content →

MutationObserver, keep an eye for DOM changes 🧐

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 

Published in Code explorations