The MutationObserver Web API

David Dal Busco
Level Up Coding
Published in
4 min readMay 11, 2021

--

An introduction to the MutationObserver Web API that provides the ability to watch for changes being made to the document.

Source forum resetera

I recently developed multiple features across projects with the help of the MutationObserver Web API. A bit to my surprise, I noticed that some colleagues never had used it or, even heard about it before. That’s why I got the idea for this blog post.

Introduction

The MutationObserver interface provides the ability to watch for changes being made the DOM tree (source MDN Web Docs).

It is a web feature, natively implemented in all browsers (yes even Internet Explorer v11 according to Caniuse), which allows us to detect when changes are made to a document, to the web page.

In Other Words

I dislike “The Last Stand” movie but, do you remember when Rogue gets the vaccine (1) to remove her powers (2)? Without any other information, we still don’t know if the cure was effective or not. To resolve the question (3), we would have to try our luck and get in contact but, without knowing what result to expect. On the other hand, thanks to his psychokinesis power, professor X would be able to detect the mutation (4) and knows if it worked out or not.

Our web page follows the same idea.

When we apply a modification to the DOM (1), such as modifying a tag or an attribute, with or without framework, it is interpreted and rendered by the browser (2). Even though the operation is really fast, if we query (3) the DOM elements touched by our changes right afterwards, we cannot be 100% sure that the modifications were already applied. Fortunately, thanks to the MutationObserver, we can detect the mutation (4) to get to know when and if it effectively worked out.

Walk-through

To initialize a MutationObserver, you shall invoke its constructor a callback function to be called when DOM changes occur.

const observer = new MutationObserver(callback);

The callback gets as a parameter an array of the individual DOM mutations which have been applied.

To observe a targeted node and to begin receiving notification through the callback, you can invoke the…

--

--