3

So far I found how to do it in Chrome, the DOMSubtreeModified event: Is there a JavaScript/jQuery DOM change listener?

Apparently it works in Firefox and IE 9 too.

Do you know solutions for detecting DOM changes in other browsers such as Opera? And maybe older versions if IE, because I'm sure the event above doesn't work in IE 6-7-8...

Or do you know other events I could use? I'm basically looking for a way to detect if certain elements have been inserted in the document trough ajax requests...

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
Alex
  • 66,732
  • 177
  • 439
  • 641

2 Answers2

3

Opera supports the DOMNodeInserted and DOMNodeRemoved mutation events. I tested and they worked on Firefox and G. Chrome too.

$(document).bind("DOMNodeInserted, DOMNodeRemoved", function() {
    alert("DOM changed");
});

If you're targeting multiple browsers, maybe you could check if Mordenizr has any detection for DOM mutation events support, it could help you a lot to simplify these decisions.

marcio
  • 10,002
  • 11
  • 54
  • 83
  • I couldn't test it on IE, netbook ;) – marcio Jan 23 '12 at 01:51
  • DOMSubtreeModified will not be supported in Opera, and I suggest you avoid using it. One reason for both statements: it can really hurt performance. Tracking and listening to everything that happens in a document will at some point slow your app down. DOMNodeInserted and DOMNodeRemoved aren't really free of performance problems either, so if you can change your architecture and avoid them it may be better. (These events are deprecated in the next DOM events spec). – hallvors Apr 27 '12 at 08:15
1

onreadystatechange will work in IE8 and below. A DHTML behavior must be attached to the element via htc, but the htc file does not have to exist:

if (!!document.addEventListener)
  {
  $(document.documentElement).get(0).addEventListener("DOMNodeInserted", bar, false);
  }
else
  {
  $(document.documentElement).get(0).addBehavior("foo.htc");
  $(document.documentElement).get(0).attachEvent("onreadystatechange", bar);
  }
Paul Sweatte
  • 24,148
  • 7
  • 127
  • 265