Handler for dynamically created DOM nodes as they are inserted

Muhd picture Muhd · Mar 19, 2012 · Viewed 13.2k times · Source

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

nrabinowitz picture nrabinowitz · Mar 19, 2012

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)

Update: The event is deprecated. You should use a MutationObserver:

var observer = new MutationObserver(function(mutationList) {
    for (var mutation of mutationList) {
        for (var child of mutation.addedNodes) {
            child.style.color = '#c00';
        }
    }
});
observer.observe(document, {childList: true, subtree: true});

// ready? Then stop listening with
observer.disconnect();

More information here: https://developer.mozilla.org/en-US/docs/Web/API/MutationObserver