Web APIs — Mutation Observer
2 min readSep 12, 2022
What is an Mutation Observer?
- MutationObserver is a built-in object that observes a DOM element and fires a callback when it detects a change.
- It provides the ability to watch for changes being made to the DOM tree.
Basic Syntax of Mutation Observer :-
let observer = new MutationObserver(callback);
function callback (mutations) {
// do something here
}// Start observing
observer.observe(targetNode, observerOptions);// disconnect the observing
observer.disconnect();
- Create the mutation observer with the callback as argument
- Create the callback -> to pass in the observer constructor — it will be called everytime any change is made to the target DOM element.
- Start observing the targetNode using the
observe()
method. - The observe method takes 2 arguments — the target and the options to configure the observation.
- We can disconnect the observation by using the disconnect method on the observer.
The below image shows the options that can be used to configure the Mutation Observer.