Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 409
Muhd Avatar asked Mar 19 '12 22:03

Muhd


2 Answers

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

like image 189
nrabinowitz Avatar answered Sep 19 '22 23:09

nrabinowitz


If you don't have access to a library like jQuery, here is the syntax in only-JavaScript :

document.addEventListener('DOMNodeInserted', nodeInsert)

function nodeInsert () {
  event.srcElement.style.color = '#ffffff'
}

I think it should work in most browsers.

like image 31
Preview Avatar answered Sep 17 '22 23:09

Preview