DEV Community

Ganesh Patil
Ganesh Patil

Posted on

DOM Element Observer

While developing a web application sometimes requires watching changes being made on the DOM element like when an attribute of a component changes or a new child element is added or removed.

How we can observe a DOM element in Javascript?

MutationObserver is the class that will help here to add a watcher on the DOM element. this watcher can observe changes for attributes or children elements as well. This MutationObserver API works asynchronously and similar to Promise uses a microtask queue while running their callbacks. In simple words, Promise / MutationObserver has more priority than setTimeout / setIntervals using the Task queue.

Let's see how to create this observer step by step.

First, create a configuration for what exactly you want to observe i.e. attributes or child nodes also both can observe at the same time.

    const mutationConfig = { attributes: true, childList: true };
Enter fullscreen mode Exit fullscreen mode

Second, create a callback function that will call when attributes or childList are modified.

function onMutationChangeCallack(mutationConfigList) {
    for(const mutationConfig of mutationConfigList) {
        if(mutationConfig.type === 'attributes') {
            addLogs(`${mutationConfig.attributeName} attribute changed`);
        } else if(mutationConfig.type === 'childList') {
        addLogs(`childList updated. new dom element added`);
        }
    }
}
Enter fullscreen mode Exit fullscreen mode

Here inbuild attributes like a style or custom attributes like custom-data can be observed.
Third, create an object of MutationObserver class and pass onMutationChangeCallback to the constructor.

   const observer = new MutationObserver(onMutationChangeCallack);
Enter fullscreen mode Exit fullscreen mode

Then observe is the method that starts watching changes on the DOM element. Two mandatory parameters need to pass to observe method. One is the target DOM element that we need to watch and the configuration object created above.

   let target = document.getElementById('playarea');
   observer.observe(target, mutationConfig);
Enter fullscreen mode Exit fullscreen mode

There are other methods like disconnect which stops the observing functionality and a callback will not be called after that.

For more information

Please check below link of live of mutation observer api

Live Example

Mutation Observer Example

Top comments (0)