I\'m using .on() to bind events of divs that get created after the page loads. It works fine for click, mouseenter... but I need to know when a new div of class
3 years of experience later, this is how I listen to "element of a certain class added to the DOM": you simply add a hook into the jQuery html() function, like this:
function Start() {
var OldHtml = window.jQuery.fn.html;
window.jQuery.fn.html = function () {
var EnhancedHtml = OldHtml.apply(this, arguments);
if (arguments.length && EnhancedHtml.find('.MyClass').length) {
var TheElementAdded = EnhancedHtml.find('.MyClass'); //there it is
}
return EnhancedHtml;
}
}
$(Start);
This works if you're using jQuery, which I do. And it doesn't rely on the browser-specific event DOMNodeInserted, which is not cross-browser compatible. I also added the same implementation for .prepend()
Overall, this works like a charm for me, and hopefully for you too.