Muhd Muhd - 1 month ago 7
Javascript Question

Handler for dynamically created DOM nodes as they are inserted

I enjoy running custom scripts on pages that I do not own or control. Many times these pages have dynamically created content that I would like to apply a function to.

Is this possible? If so, how can I do this? Ideally I am looking for something live jQuery's

live
method, except instead of binding an event like
click
it would be more like an event that happens when the element is loaded in the DOM.
load
event would work for some elements but I don't think for all...

For this question, assume that you cannot look at or change the code that is inserting the DOM nodes. I would like a technique that I could use in a userscript or bookmarklet that could be used across multiple unrelated sites.

Edit: I am looking for something to use on my invert colors bookmarklet: JavaScript: Invert color on all elements of a page

Answer

Assuming you're running a browser like Firefox or Chrome, you could listen for the DOMNodeInserted event:

$(document).on('DOMNodeInserted', function(e) {
    $(e.target).css({ color : '#c00' });
});

$('body').append('<div>test</div>');‚Äč

Fiddle: http://jsfiddle.net/VeF6g/ (probably fails in IE)