jquery detecting div of certain class has been added to DOM

前端 未结 6 1767
失恋的感觉
失恋的感觉 2020-12-02 06:49

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

6条回答
  •  余生分开走
    2020-12-02 07:50

    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.

提交回复
热议问题