How do I check whether a jQuery element is in the DOM?
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).
I just realized an answer as I was typing my question: Call
$foo.parent()
If $f00
has been removed from the DOM, then $foo.parent().length === 0
. Otherwise, its length will be at least 1.
[Edit: This is not entirely correct, because a removed element can still have a parent; for instance, if you remove a <ul>
, each of its child <li>
s will still have a parent. Use SLaks' answer instead.