How do I check whether a jQuery element is in the DOM?

Let's say that I define an element

$foo = $('#foo');

and then I call

$foo.remove()

from some event. My question is, how do I check whether $foo has been removed from the DOM or not? I've found that $foo.is(':hidden') works, but that would of course also return true if I merely called $foo.hide().


Solution 1:

Like this:

if (!jQuery.contains(document, $foo[0])) {
    //Element is detached
}

This will still work if one of the element's parents was removed (in which case the element itself will still have a parent).

Solution 2:

How about doing this:

$element.parents('html').length > 0