HomeTutorsContact
JavaScript
How to detect changes in DOM?
Gulshan Saini
June 04, 2020
1 min

I had a requirement where I need to know if something got changed in the DOM i.e. any element was added/removed or attribute(s) were modified.

I needed a simple mechanism to detect all sorts of DOM changes and then I learned about MutationObserver.

MutationObserver lets us watch for changes being made in the DOM tree. We can even target the specific DOM element to watch for changes.

Logging DOM changes

Let’s start with simple markup

First, we need to select the target node which we want to observe for any changes

Next, we need to create an instance of MutationObserver

MutationObserver accepts a callback that gets called when element under observation mutates.

Let’s create callback logMutations and pass it to MutationObserver. The callback function takes two input parameters i.e. mutations & observer which invoked the callback.

In logMutations callback function, we are iterating over the mutations array and logging them to console.

You can even filter the results based on mutation.type as follows

Last, thing is to start observing the target element as follows

Last line in above code i.e. observer.observe accepts following inputs

  • target element i.e. list in our case
  • a configuration object of what need to be tracked. At a minimum, one of following properties can be set to true so that they can be tracked
    • childList - Set to true if mutations to target’s children are to be observed.
    • attributes - to observe attributes, set it to true
    • characterData - target’s data are to be observed.
    • subtree - target’s descendants are to be observed

For complete list please visit MDN docs

Our MutationObserver is ready to log items on console. Let’s quickly add a button to dynamically add items to list

We will be calling following function when user click on Add New Item button

Lets see it in action

Output

Open developer console and click on “Add New Item” button. You should see following output in console

Summary

  • MutationObserver can be used to detect changes in element, attribute, child nodes etc.
  • MutationObserver instance takes callback function
  • MutationObserver callback function accepts inputs i.e. mutations and observer

Tags

#dom-manipulation
Previous Article
How to create circle in SVG?

Subscribe to our newsletter!

We'll send you the best of our blog just once a month. We promise.

Related Posts

How to iterate through NodeList using Javascript?
July 09, 2020
1 min
© 2020, All Rights Reserved.

Quick Links

Advertise with usContact Us

Social Media