jquery detecting div of certain class has been added to DOM

前端 未结 6 1758
失恋的感觉
失恋的感觉 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:28

    Previously one could hook into jQuery's domManip method to catch all jQuery dom manipulations and see what elements where inserted etc. but the jQuery team shut that down in jQuery 3.0+ as it's generally not a good solution to hook into jQuery methods that way, and they've made it so the internal domManip method no longer is available outside the core jQuery code.

    Mutation Events have also been deprecated, as before one could do something like

    $(document).on('DOMNodeInserted', function(e) {
        if ( $(e.target).hasClass('MyClass') ) {
           //element with .MyClass was inserted.
        }
    });
    

    this should be avoided, and today Mutation Observers should be used instead, which would work like this

    var observer = new MutationObserver(function(mutations) {
        mutations.forEach(function(mutation) {
            console.log(mutation)
            if (mutation.addedNodes && mutation.addedNodes.length > 0) {
                // element added to DOM
                var hasClass = [].some.call(mutation.addedNodes, function(el) {
                    return el.classList.contains('MyClass')
                });
                if (hasClass) {
                    // element has class `MyClass`
                    console.log('element ".MyClass" added');
                }
            }
        });
    });
    
    var config = {
        attributes: true,
        childList: true,
        characterData: true
    };
    
    observer.observe(document.body, config);
    

提交回复
热议问题