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.

index.html

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

months.js

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

--

--

Shuvo Habib
Shuvo Habib

Written by Shuvo Habib

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