jquery detecting div of certain class has been added to DOM

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

    Two additions to adeneo's answer:

    (1) we can change the line

    return el.classList.contains('MyClass');
    

    To

    if( el.classList ) {
        return el.classList.contains('MyClass');
    } else {
        return false;
    }
    

    So we won't see the "Uncaught TypeError: Cannot read property 'contains' of undefined" error.

    (2) add subtree: true in config to find added nodes recursively in all added elements.

提交回复
热议问题