Web APIs — Mutation Observer

Eishta Mittal
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.
Content image

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();
  1. Create the mutation observer with the callback as argument
  2. Create the callback -> to pass in the observer constructor — it will be called everytime any change is made to the target DOM element.
  3. Start observing the targetNode using the observe() method.
  4. The observe method takes 2 arguments — the target and the options to configure the observation.
  5. 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.

--

--

Eishta Mittal
Eishta Mittal

Written by Eishta Mittal

Software Engineer passionate about Frontend Engineering

No responses yet