Bart Simons

dom changes

A 1 post collection


Detect and monitor DOM changes with MutationObserver

 •  Filed under monitor, javascript, detect, dom changes, mutationobserver

The MutationObserver JavaScript API allows a developer to actively watch for DOM changes, so that if something gets changed, added or removed within the boundaries of the specified DOM node, a callback function will be triggered.

Browser support for this API is pretty good as well. All major modern browsers do support MutationObserver, but please note that IE10 and lower are not supported unless you use some sort of shim or polyfill for this.

Getting started is very easy as well:

// Step 1: Create a new MutationObserver object
var observer = new MutationObserver( function(mutations) { // this is the callback function } )

// Step 2: Observe a DOM node with the observer as callback
observer.observe(document.querySelector("table"), { attributes: true, childList: true, attributeOldValue: true })  



As an example I have built up a table to watch out for DOM changes:

<table id="demoTable" class="table">  
  <thead>
    <tr>ID</tr>
    <tr>E-mail</tr>
  </thead>

  <tbody>
    <tr>
      <td>1</td>
      <td>todd@localhost</td>
    </tr>
    <tr>
      <td>2</td>
      <td>ted@localhost</td>
    </tr>
    <tr>
      <td>3</td>
      <td>root@localhost</td>
    </tr>
    <tr>
      <td>4</td>
      <td>bart@localhost</td>
    </tr>
  </tbody>
</table>  



And here is the JavaScript code that goes with this:

var observer = new MutationObserver(function(mutation) {  
console.log(mutation)  
})

var observerConfig = {  
  attributes: true,
  childList: true,
  attributeOldValue: true,
  characterData: true
}

const tableRows = document.querySelectorAll("#appUsers tr")

for (i = 0; i < tableRows.length; i++)  
{
  observer.observe(tableRows[i], observerConfig);
}



Try to destroy, add or recreate td elements inside the table and you will get an array of MutationRecord objects returned within your browsers' console. Please note that when you edit the node's innerHTML, nothing will get triggered. I don't know if this is a bug in Safari (I only tested this in Safari, FYI) or something by design.