check if cached jquery object is still in DOM

前端 未结 4 988
情书的邮戳
情书的邮戳 2021-01-04 02:52

Does anyone know how to tell if a cached jQuery object has gone stale, e.g. is no longer in the DOM? For example:

var $cached_elem = $(\'.the_button\');

//         


        
4条回答
  •  庸人自扰
    2021-01-04 03:03

    if($elem.closest('body').length > 0) seems like it could do the trick.

    $(function() {
        var $button = $(".the_button");
        alert (isStale($button));
        $button.remove();
        alert (isStale($button));
    });
        
    function isStale($elem)
    {
        return $elem.closest("body").length > 0;
    };
    
    
    Hello World

    Edit: Updated in response to Yi Jiang's comment so that it will return correctly if its parent element is removed

    Edit 2: Updated in response to lonesomeday's comment - changed parents() to 'closest()` for performance improvement

提交回复
热议问题