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() .


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).


如何做到这一点:

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

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.

链接地址: http://www.djcxy.com/p/83860.html

上一篇: ASP.NET Web Api在返回404时返回200 OK

下一篇: 如何检查jQuery元素是否在DOM中?