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 lets us watch for changes being made in the DOM tree. We can even target the specific DOM element to watch for 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 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.
observer which invoked the callback.
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
listin our case
For complete list please visit MDN docs
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
Open developer console and click on “Add New Item” button. You should see following output in console
MutationObservercan be used to detect changes in element, attribute, child nodes etc.
MutationObserverinstance takes callback function
MutationObservercallback function accepts inputs i.e. mutations and observer