Listening to DOM changes by Javascript Web API, Mutation Observer (hint: It’s the best practice)

Shuvo Habib
4 min readOct 31, 2018

“MutationObserver” is a Web API provided by modern browsers for detecting changes in the DOM. By using this API you can listen to changes in DOM, like added or removed nodes, attribute changes or changes in the text content of text nodes and make changes.

Web apps are getting complex on the client-side nowadays. You have to do a lot by listening to DOM changes. For example, you want to send a real-time notification to user from a DOM change or you’re using a JS framework that has different behaviour for a different kind of change, or you have to do a thing based on JS plugin’s return value.

Polling” with setInterval API is one of the few alternatives of Mutation Observer. Let’s have a look at it for better understanding actually what “Mutation Observer” do.


<!DOCTYPE html>
<ul class="months"></ul>


addMonth is a simple function that’s returning a random name of a month or number from the nameOfMonth array after 2 seconds.

Let’s add a polling function after it.

To print the DOM Change, CheckMonth needs to check every second if anything changes in the DOM and after a check it prints away from the outerHTML. After it gets the change it clear out the Interval. setInterval WebAPI can set up a task that would periodically check if any changes have occurred. Naturally, this method significantly degrades web app/website performance.

MutationObserver Implementation:

Implementing MutationObserver into the app is rather easy. You need to create a MutationObserver instance by passing it a function that…



Shuvo Habib

I'm a storyteller about UX, Frontend dev technologies, and A/B testing