24

Are there any DOM mutation events in JQuery or in vanilla Javascript that fire cross browser?

To clarify, say I have a script on my page which inserts a div into the body. I don't have access to the script and I don't know when the div has been inserted. I was wondering if there's a DOM mutation event that I can add a listener for, to know when an element has been inserted. I know I can use a timer to periodically check for the insertion but, I don't really like the overhead that this would impose.

12
  • Could you be a little more specific please?
    – pimvdb
    Oct 7, 2011 at 20:51
  • 1
    I thought all the jQuery events fired cross-browser... Oct 7, 2011 at 20:52
  • 1
  • 1
    Such question calls a why. It makes me suspect that there is an ajax call and some display being done. In such case there is other solutions to that kind of issue. Otherwise, if you know what you are doing and why, I suggest as a poor's man solution to check periodically the length of the body node.
    – Olivvv
    Oct 12, 2011 at 9:24
  • 1
    Well, the whole problem is that i don't have control over the script injecting the data into the body. If i did, the obvious soulution would have been to add a callback. Oct 12, 2011 at 12:00

6 Answers 6

24
+50

This is certainly a hack, but why not patch the underlying DOM methods used to insert the nodes? There are a couple ways to do this:

A. You know what specific element will be appended to:

var c = document.getElementById('#container');
c.__appendChild = c.appendChild;
c.appendChild = function(){
     alert('new item added');
     c.__appendChild.apply(c, arguments); 
}

fiddle demo for A

B. You know what type of element will be appended to:

HTMLDivElement.prototype.__appendChild = HTMLDivElement.prototype.appendChild;
HTMLDivElement.prototype.appendChild = function(){
    alert('new item added');
    HTMLDivElement.prototype.__appendChild(this,arguments); 
}

fiddle demo for B

(Note that solution B is not supported by IE < 8 or any other browser which does not support DOM prototypes.)

This same technique could just as easily be used on all the underlying DOM mutation functions such as insertBefore, replaceChild or removeChild.

That's the general idea, these demos could be adapted for pretty much any other use case -- say you want to cast a wide net and catch all additions regardless of type AND make sure it works across all browsers everything but IE < 8? (see example C below)


UPDATE

C. Recursively walk the DOM, swap out the function on every element to trigger a callback, and then apply the same patch to any children being appended.

var DOMwatcher = function(root, callback){
  var __appendChild = document.body.appendChild;

  var patch = function(node){
    if(typeof node.appendChild !== 'undefined' && node.nodeName !== '#text'){
      node.appendChild = function(incomingNode){
        callback(node, incomingNode);
        patch(incomingNode);
        walk(incomingNode);
        __appendChild.call(node, incomingNode);
      };
    }
    walk(node);  
  };

  var walk = function(node){
    var i = node.childNodes.length;
    while(i--){
      patch(node.childNodes[i]);
    }
  };

  patch(root);

};

DOMwatcher(document.body, function(targetElement, newElement){ 
   alert('append detected');    
});

$('#container ul li').first().append('<div><p>hi</p></div>');
$('#container ul li div p').append('<a href="#foo">bar</a>');

fiddle demo for C

UPDATE 2

As Tim Down commented, the above solution also won't work in IE < 8 because appendChild is not a Function and does not support call or apply. I suppose you could always fall back to the clunky but trusty setInterval method if typeof document.body.appendChild !== 'function'.

5
  • 1
    This won't work in IE < 9 and is generally dodgy since host methods such as appendChild() are not required to be Function objects (and indeed aren't in IE < 9).
    – Tim Down
    Oct 16, 2011 at 15:31
  • 1
    @TimDown Shoot! You're right, in browsers where appendChild is not a Function this solution will fail because it doesn't respond to call or apply. Good catch, I've updated the answer to reflect this. However, you'll find that the code above does work in IE 8. Oct 17, 2011 at 4:19
  • Ah, OK. I was unsure about IE 8, I confess.
    – Tim Down
    Oct 17, 2011 at 8:30
  • If you are looking for an alternative to this method, here is jqui.net/jquery-projects/jquery-mutate-official which can also allow you to add events yourself and keep a watch for almost any change, class name change, height change, width change.
    – Val
    Sep 20, 2012 at 9:02
  • Fascinating, and terrifying. +1! Sep 15, 2013 at 18:03
8

There are some deprecated DOM mutation events, such as DOMNodeInserted and DOMNodeInsertedIntoDocument that still work for me in Chrome 14 and IE9.

See an example at http://jsfiddle.net/Kai/WTJq6/

See them all on the W3C draft at http://www.w3.org/TR/DOM-Level-3-Events/

2
  • 3
    IE 9 is the first version of IE that had DOM mutation events, so this won't work in IE < 9. While these events are deprecated, the spec for their replacement is not yet complete so they won't be going away for a while yet.
    – Tim Down
    Oct 11, 2011 at 23:19
  • Great to know about IE, since I don't use it much. Btw, OT: I discovered your Rangy lib yesterday -- its awesome, ty. :)
    – Kai
    Oct 12, 2011 at 20:45
4

JCADE (JQuery Create and Destroy Events) will do this. It uses behaviors for IE and DOM mutation events for other browsers. It does not use timing events and does not wrap JQuery methods like livequery.

https://github.com/snesin/jcade


    $( document ).create( "a", function( event ) {
      alert( event.target );
    });

3

Not without a plugin, I believe, but I wouldn't be surprised if I'm wrong.

My research has found a a few to choose from.

Here's one: http://plugins.jquery.com/project/mutation-events

Here's another: https://www.adaptavist.com/display/jQuery/Mutation+Events

2
  • 1
    This looked promising until i looked at the script code and realized they are not using jQuery to insert the div into the DOM. Oct 7, 2011 at 21:20
  • Hmm, shucks. I'll admit to not having attempted this, so I can't really speak to how they work. Sorry. Oct 7, 2011 at 21:31
0

If you are looking for an alternative to this method, here is http://www.jqui.net/jquery-projects/jquery-mutate-official/ which can also allow you to add events yourself and keep a watch for almost any change, class name change, height change, width change.

0

The livequery plugin can be used for this. In version 1.x a timer was used to periodically check for any changes. However, the newer version 2.x branch seems to be working without periodical timeout (untested).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.