Eric Chen Eric Chen - 5 months ago 30
Javascript Question

intercepting [HTMLElement].innerHTML modifications in Chrome

I have a function called x(). I want to call x() every time an arbitrary node's innerHTML property is being changed (please note that I want x() to be called for all nodes, not just 1 node). Initially, I thought innerHTML was a function of the HTMLElement object, and wanted to monkey patch it, but after playing around in Chrome's Javascript console, I failed to find the innerHTML function in the HTMLElement object.

I also thought about using the DOMAttrModified event ( but it's not supported in Chrome. Any suggestions are welcome.


Depending on what you are developing for and the browser support you need (it sounds like just Chrome, and hopefully just modern Chrome), you can look into the MutationObserver interface (exampled borrowed and slightly modified from the Mozilla Hacks Blog:

MutationObserver = window.MutationObserver || window.WebKitMutationObserver;

// create an observer instance
var observer = new MutationObserver(function(mutations) {
  mutations.forEach(function(mutation) {

// configuration of the observer:
var config = { attributes: true, childList: true, characterData: true };

// select the target nodes
).forEach(function(target) {
    observer.observe(target, config);

// later, you can stop observing

More on MutationObservers can be found here:

This was implemented in Chrome 18 & Firefox 14.