Detect if a jQuery object is on the page or not

前端 未结 4 1575
温柔的废话
温柔的废话 2021-01-07 18:11

Given a jQuery object, $j, I need to know if it represents something that is already on the page or if it is something that has not yet been put on the page. Fo

4条回答
  •  隐瞒了意图╮
    2021-01-07 18:47

    I'd probably just check to see if the element can reach the body element:

    $j.closest('body').size()>0
    

    As you noted in other comments, this would fail in some exceptional cases where you are handling extra body elements. If you really want to detect those situations, I guess you could check to see if you have multiple $(body) elements but I suspect that such extreme cases will get out of control pretty quickly.

    This "is-probably-attached-to-page" check could be turned in to a bona-fide jQuery selector, too:

    $.expr[':'].isProbablyAttached = function(obj){
    
        return $(obj).closest('body').size()>0;
    };
    
    // Usage:
    $('.someClasses:isProbablyAttached').doSomething();
    

提交回复
热议问题