jquery detecting div of certain class has been added to DOM

jquery

Solution

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.

Problem

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 MyClass has been added. I'm looking for this: ``` $('#MyContainer').on({ wascreated: function () { DoSomething($(this)); } }, '.MyClass'); ``` How do I do this? I've managed to write my entire app without a plugin and I want to keep it that way. Thanks.

Original source

Related problems