check if cached jquery object is still in DOM

前端 未结 4 963
情书的邮戳
情书的邮戳 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: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
    }
    

提交回复
热议问题