How to use Javascript Mutation observer

What is mutation observer

In this blog, we are implementing a basic mutation observer example that will observe the DOM changes and fire the events. So first, we have to understand what a mutation observer is. and how to use mutation observer in javascript

What Is a Mutation Obsever ?

The MutationObserver interface offers the potential to observe for adjustments being made to the DOM tree. it’s far designed as a replacement for the older Mutation events function, which turned into a part of the DOM3 activities specification.

Let us take an example in real life sanario, suppose some data in the website rendering after 3 seconds on delay, it could be rendering by sever, so on page load we are not able to get data in our dom because of this server side delay, and we are not able to apply javascript, or target server side DOM element by javascript because it is not present in DOM at the time of first page load, So to observer that DOM changes and apply javascript at that time when server side DOM element got injected in HTML page we use mutation observer .

let get more clear with the help of below diagram for Mutation Observer

Simple Mutation Observer Method

Lets start with simple mutation observer method and understand step by step

In the above code we have to select an element from DOM on which we want to observe change or in which we have to observer the data coming from API.

In config we will define if we want to observe a subtree modification like child element injected , and any attribute modification on div , or and child list injected like ul li

The above one is the callback function which will check all the mutaions list defind and observe change in them, you can see the condition mutation.type === “childList” that will check if any child element is added from server on by delay of if mutation.type === “attributes” it will check for any attribute modification.

targetNode is the target element pass in method obsever and config is the const which will pass what wen need to observe in mutations const config = { attributes: true, childList: true, subtree: true };

Now let us go through a simple example of the above use case, where after 5 seconds we will insert an element into the DOM that acts as an API and make some changes to that element through mutation observer.

let create and html structure first as below

HTML

Your can see there are three section in above code , in second section we have added an id with name server-data
in which we are going to inject a div with class data after some delay so that it can be observe by mutation observer

So now we will write a javascript code to observe that element with id=”server-data”.

In above code we have defined const targetNode = document.getElementById(“server-data”); which is an ID it will observe server-data div so if any change modified inside that div willbe observe by mutation observer , now lwt us go thrugh the working demo of above code which will chean the backgournd coloue of the mutated element in DOM

DEMO

Wait for 4 seconds

Element Already present in DOM

this is container data

Element to be injected after some time

Element Already present in DOM

this is container data
In above demo you will see after some time when data got injected from server the background colour and text is changed, because through mutation observer we have added a class when any subtree modification happens on the targeted mutation div.

DEMO FILE

Download the demo file and impliment in your code

Further reading

  • React UseEffect | simplifyScript

    Understanding the useEffect hook in React

    In this article, we will learn about another React hook called useEffect(), through this article you will be able to understand what is react useEffect Hook and how to use useEffect() hook in react, this is most communally used hook after useState() hook, we mostly use this hook in every component on react now first […]
  • React useState function

    How to Use useState Hook in React Application

     In a React application, normal vanilla JavaScript may not work for some concepts. For example, if I want to toggle a class on a button click or add and remove classes, I might need to show a popup on the website. This can be easily achieved in vanilla JavaScript using the element.classList.toggle(“newClass”) method, allowing us to add […]
  • javascript DOm manipulation - simplifyscript

    What is DOM manipulation in javascript 

    In this article, we will explore JavaScript DOM manipulation, a key feature of JavaScript that allows developers to modify the Document Object Model (DOM) of a webpage. DOM manipulation enables you to dynamically alter the content and structure of HTML documents. To grasp this concept thoroughly, we’ll start by defining what the DOM is and […]