To be clear: I am not asking how to put existing hooks onto new DOM elements. I know about the live() function and the old livequery plugin. I am asking something else.

What I want to know is how to hook onto the very creation of new DOM elements. The reason I'm asking is I'm creating a third-party user JS script that doesn't have control over first-party scripts. Those first-party scripts (which are obfuscated) update the page periodically by adding new DOM elements. I want to execute code after those elements are added.

Using $( '...' ).bind( 'ajaxSuccess', function() ..... ) works for some additions, but not all of them.

No correct solution


If they are always being added with the document.createElement method you could simply replace it and do your tracking in there.

document.replacedCreateElement = document.createElement;
document.createElement = function(tagName) {
    //do your tracking  

I'm not sure why you ask if you know about livequery. Livequery will allow you to hook into arbitrary new DOM elements. Outside of this, the only thing I know to do is hook into the DOM methods (such as appendChild etc...)

The live() function which was integrated into jQuery actually isn't the full livequery implementation. (Resig thought it was too much functionality to be integrated without blowing the code size up too far)

In live(), what is missing is the following type function:

$('*').livequery(function() {
 // do something

Use this, and it should catch any additions.

Well, I went with this pair, which seems to fire on the desired DOM updates within 20 seconds or less:

$( '#someid' ).bind( 'ajaxSuccess', function() { ... } );
$( '#someid' ).ajaxSuccess( function( e, r, s ) { ... } );

I'd rather not have to slow page loading by depending on livequery, and the replacedCreateElement solution thrashed the CPU.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow