·

photo credit: P3300796 via photopin (license)

Detect changes on HTML element with the MutationObserver

Recently I ran in a situation of which I’m sure some of you also encountered at some point: I had to perform an action when the class of an element changed. This change was done by an external plugin and I didn’t want to edit to source of that plugin to provide a hook.
So how did I do this?

How to monitor changes on an element with JavaScript

I’ve encountered this scenario before, and a much used – but very ugly – solution is to simply poll for a specific change using a setInterval()  in JavaScript. Needless to say, this works but it has very drawbacks.
But then I stumbled upon the MutationObserver. What it does is actually exactly what I was looking for: it creates an observer that polls an element for changes (mutations) and executes a function when a change is detected. The implementation is actually pretty simple:

The above example polls myElement  and fires a function when any of it’s attributes are changed. It only checks for attributes in this example, since I set {attributes: true}  when I started observing, but there are more options that can be set. For example: you can also fire a function when the content of the node is changed, or when there are children added.
When you’re done observing, you can stop observing by using the disconnect() -method:

Browser compatibility

As with all cool stuff on the Internet, all major browser support it (Internet Explorer from version 11 and up). A polyfill for older browsers can be found here.

Visitors give this article an average rating of 3.9 out of 5.

How would you rate this article?

Leave a Reply