How to detect new element creation in jQuery?
You can use the arrive.js library that I developed for the exact same purpose (it uses MutationObserver internally). Usage:
document.arrive('a', function(){
// 'this' refers to the newly created element
var newElem = this;
});
You can use the .livequery()
plugin for this, it runs for each element, including new ones, like this:
$("a").livequery(getLinkCount);
However, this plugin is out-of-date and is not recommended for current versions of jQuery.
It's usually easier to do this when you create the elements though, for example if you're doing it after AJAX requests, the .ajaxComplete()
handler may be a good place, for example:
$(document).ajaxComplete(getLinkCount);
This would run after each request, and since you normally create elements in your success
handler, they would already be present when this complete handler runs.
You could use the DOMSubtreeModified event. For example:
$(document).bind('DOMSubtreeModified',function(){
console.log("now there are " + $('a').length + " links on this page.");
})