Bart Simons

Bart Simons


Thoughts, stories and ideas.

Bart Simons
Author

Share


Tags


.net .net core Apache C# CentOS LAMP NET Framework Pretty URLs Windows Server WireGuard WireGuard.io access log add analysis android api at the same time authentication authorization automate automation azure azurerm backup bash basics batch bootstrap build capture cheat sheet chromium chroot class cli click to close code snippet command line commands compile compiling compression containers control controller controlling convert cpu usage create credentials csv csvparser curl data dd deployment desktop detect devices disable diskpart dism distributed diy docker dom changes dotnet core drivers ease of access encryption example export file transfer files fix folders generalize getting started ghost ghost.org gui guide gunicorn gzip html html tables icewarp igd imagex import inotify install installation interactive ios iphone itunes java javascript jquery json kiosk kotlin linux live load data loading screen lock screen loopback audio lxc lxd lxml macos manage manually message messages minio mirrored mod_rewrite monitor monitoring mutationobserver mysql nexmo nginx no oobe node node.js nodejs not installing notification notifications object storage on desktop one command openssl owncloud parallels parallels tools parse perfect philips hue play port forwarding portainer.io powershell processing ps-spotify python quick raspberry pi record rip ripping rsync rtmp save save data sbapplication scraping script scripting scriptingbridge scripts security send server service sharedpreferences sms songs sonos spotify spotify api spotlight ssh stack streaming streamlink studio sudo swarm swift sync sysprep system audio systemd tables terminal tracking tutorial twilio ubiquiti ubuntu ubuntu 18.04 ui code unifi unlock unsplash source upnp uptime usb tethering wallpapers wasapi website websites webview windows windows 10 without itunes without oobe workaround xaml

Detect and monitor DOM changes with 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.
Bart Simons
Author

Bart Simons

View Comments