Is there an onDocumentChange event?

Is there any event in Internet Explorer that fires when the DOM changes? For example:

document.attachEvent("ondocumentchange", function () { alert("you've just changed DOM!"); }); 

And when I do:

 document.appendChild(document.createElement("img")); 

A window with the text "you just changed the DOM!" appears.

I am trying to emulate "advanced" CSS selectors (like +,>, [attr]) in IE6 using Javascript. However, to work correctly with dynamic content, they must be recalculated after each change to the document.

+6
javascript internet-explorer events
source share
3 answers

Brute Force Solution:

 (function (previousInnerHTML) { return function () { if (document.body.innerHTML !== previousInnerHTML) { alert("you've just (at max 33ms ago) changed DOM"); } setTimout(arguments.callee, 33); }; })(document.body.innerHTML)(); 
+9
source share

You want to see dom mutation events - see http://en.wikipedia.org/wiki/DOM_Events and scroll down to the section on mutation events. The only problem is that the support for these events is rather fragmentary, so be careful with them. It is noteworthy that the lack of support in general in IE or Opera. Firefox, Safari and Chrome seem to be the only ones.

Something like:

 document.addEventListener("DOMSubtreeModified", function () { alert("you've just changed DOM!"); }); 

According to http://www.quirksmode.org/dom/events/index.html for these events you need to use addEventListener, not attachEvent. The event appears to be bubbling, so it should be fine.

+3
source share

From above my head, this may work:

 document.body.attachEvent('onpropertychange', function(event) { if (event.propertyName !== 'innerHTML') return; alert("you've just changed DOM!"); }); 

It depends on the proprietary property of IE [onPropertyChange event] ( http://msdn.microsoft.com/en-us/library/ms536956(VS.85).aspx) - since the innerHTML document will change whenever a node, but:

  • It may not work with certain types of properties. I believe that innerHTML will function as a "getter" as it will only be recounted when retrieved.

  • It would also catch a lot of false positives - many other things would change innerHTML , which would have nothing to do with node insertion. You can mitigate this by listening to a specific element, rather than the entire document.

+1
source share

All Articles