如何检查 jQuery 元素是否在 DOM 中?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3086068/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How do I check whether a jQuery element is in the DOM?
提问by Trevor Burnham
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()
.
从某个事件。我的问题是,如何检查 $foo 是否已从 DOM 中删除?我发现这$foo.is(':hidden')
有效,但如果我只是调用$foo.hide()
.
回答by SLaks
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).
如果元素的父元素之一被删除,这仍然有效(在这种情况下,元素本身仍然有一个父元素)。
回答by Kushagra Gour
How about doing this:
这样做怎么样:
$element.parents('html').length > 0
回答by Trevor Burnham
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.
如果$f00
已从 DOM 中删除,则$foo.parent().length === 0
. 否则,其长度至少为 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.
[编辑:这并不完全正确,因为被移除的元素仍然可以有一个父元素;例如,如果您删除 a <ul>
,它的每个子<li>
s 仍将有一个父级。请改用 SLaks 的答案。
回答by Jaakko Salomaa
Since I'm unable to respond as a comment (too low karma I guess), here's a full reply. The fastest way is easily to unroll the jQuery check for browser support and to shave the constant factors to minimum.
由于我无法作为评论做出回应(我猜是业力太低了),这是一个完整的回复。最快的方法是轻松展开 jQuery 检查以获取浏览器支持,并将常量因素降至最低。
As seen also here - http://jsperf.com/jquery-element-in-dom/28- the code would look like this:
如此处所示 - http://jsperf.com/jquery-element-in-dom/28- 代码如下所示:
var isElementInDOM = (function($) {
var docElt = document.documentElement, find,
contains = docElt.contains ?
function(elt) { return docElt.contains(elt); } :
docElt.compareDocumentPosition ?
function(elt) {
return docElt.compareDocumentPosition(elt) & 16;
} :
((find = function(elt) {
return elt && (elt == docElt || find(elt.parentNode));
}), function(elt) { return find(elt); });
return function(elt) {
return !!(elt && ((elt = elt.parent) == docElt || contains(elt)));
};
})(jQuery);
This is semantically equivalent to jQuery.contains(document.documentElement, elt[0]).
这在语义上等同于 jQuery.contains(document.documentElement, elt[0])。
回答by lxg
Probably the most performative way is:
可能最具表现力的方式是:
document.contains(node); // boolean
This also works with jQuery:
这也适用于 jQuery:
document.contains($element[0]); // var $element = $("#some-element")
document.contains(this[0]); // in contexts like $.each(), `this` is the jQ object
Source from MDN
来自MDN
Note:
笔记:
回答by Erez Pilosof
instead of iterating parents you can just get the bounding rect which is all zeros when the element is detached from dom
而不是迭代父母,你可以得到边界矩形,当元素与 dom 分离时,它全为零
function isInDOM(element) {
var rect=element.getBoundingClientRect();
return (rect.top || rect.bottom || rect.height || rect.width)?true:false;
}
if you want to handle the edge case of a zero width and height element at zero top and zero left you can double check by iterating parents till the document.body
如果您想处理零顶部和零左零宽度和高度元素的边缘情况,您可以通过迭代父级直到 document.body 进行双重检查
回答by Brian Button
I liked this approach. No jQuery and no DOM search. First find the top parent (ancestor). Then see if that is the documentElement.
我喜欢这种方法。没有 jQuery,也没有 DOM 搜索。首先找到顶级父级(祖先)。然后看看那是不是documentElement。
function ancestor(HTMLobj){
while(HTMLobj.parentElement){HTMLobj=HTMLobj.parentElement}
return HTMLobj;
}
function inTheDOM(obj){
return ancestor(obj)===document.documentElement;
}
回答by Rodrigo Zoff
jQuery.fn.isInDOM = function () {
if (this.length == 1) {
var element = this.get(0);
var rect = element.getBoundingClientRect();
if (rect.top + rect.bottom + rect.width + rect.height + rect.left + rect.right == 0)
return false;
return true;
}
return false;
};
回答by Ian Bytchek
Agree with Perro's comment. It can also be done like this:
同意佩罗的评论。也可以这样做:
$foo.parents().last().is(document.documentElement);
回答by stevematdavies
Why not just: if( $('#foo').length === 0)...
?
为什么不只是: if( $('#foo').length === 0)...
?