check if cached jquery object is still in DOM

前端 未结 4 964
情书的邮戳
情书的邮戳 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;
    };
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <div>
        <span class="the_button">Hello World</span>
    </div>

    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

    0 讨论(0)
  • 2021-01-04 03:07

    If the selector hasn't changed, just reinitialize it:

    var $cached_elem = $('.the_button');
    // code that might remove some elements of $cached_elem
    $cached_elem = $('.the_button');
    

    If you want to avoid duplicating the selector string, use the selector property of the original jQuery object:

    var $cached_elem = $('.the_button');
    // code that might remove some elements of $cached_elem
    $cached_elem = $($cached_elem.selector);
    if ($cached_elem.length) {
      // element still exists
    }
    
    0 讨论(0)
  • 2021-01-04 03:09

    The native document.contains() method should be faster than jQuery to determine if a cached jQuery element exists in the DOM.

    if (document.contains($cached_elem[0])) {
        // Element is still in the DOM
    }
    
    0 讨论(0)
  • 2021-01-04 03:10

    In a slightly variant case, one can directly compare the native DOM element wrapped by the jQuery object $cached_elem.

    $cached_elem[0] === $($cached_elem.selector)[0]
    

    Besides checking if the $cached_elem is still in DOM, this can tell you if it's still the original DOM element, rather than a re-created one with same attributes after certain/partial page refresh.

    0 讨论(0)
提交回复
热议问题