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\');
//
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;
};
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