UI/UX Design

Detecting DOM changes with javascript using MutationObserver

MutationObserver is a javascript function which gives developers the possibility to detect and react to changes in a DOM.

Let’s start by creating a simple HTML page which contains a button that will append a div to the DOM when is clicked.

<!DOCTYPE html>
<html lang="en">
    <meta charset="UTF-8">
    <title>MutationObserver example</title>
    <button id="btn">Create DIV</button>

    <script src="app.js"></script>

Now in the app.js file we detect the click action and append the div.

let elem = document.getElementById('btn');
let div = document.createElement('div');
div.innerHTML = 'This is a DIV';

elem.addEventListener('click', e => {

The MutationObserver takes a callback function as a parameter which will be called on each DOM mutation. The observer will call this function with two arguments. The first is an array of objects, each of type MutationRecord. The second is this MutationObserver instance.

To create an observer all you have to do is:

const observer = new MutationObserver(mutation => {
  console.log('DOM mutation detected');

Once you created the observer you can start observing the DOM by calling observer.observe(Node target, MutationObserverInit options). This function registers the MutationObserver instance to receive notifications of DOM mutations on the specified node.

The first parameter will be the node on which to observe DOM mutations and the second parameter will be a MutationObserverInit object that specifies which DOM mutations should be reported.

observer.observe(document.body, {
  childList: true,
  attributes: true,
  subtree: true,
  characterData: true

You can find all properties for the MutationObserverInit here


UI/UX Designer & Front-end Engineer based in Dublin currently working @IBM.
I write about: UI/UX Design, Javascript, HTML, CSS, React JS and React Native

Add comment