如何检查DOM中是否有jQuery元素?

时间:2022-10-22 07:20:06

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(),当然也会返回true。

11 个解决方案

#1


216  

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

如果删除了其中一个元素的父元素(在这种情况下,元素本身仍然有父元素),这仍然有效。

#2


21  

How about doing this:

如何做:

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

#3


5  

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()。长度= = = 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.

[编辑:这不是完全正确的,因为删除的元素仍然可以有父元素;例如,如果您删除一个

    ,它的每个子
  • s仍然有一个父元素。使用SLaks回答。

  • 年代仍然有一个父元素。使用SLaks回答。

#4


4  

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,英语教学[0])。

#5


1  

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;
}

#6


0  

Agree with Perro's comment. It can also be done like this:

同意Perro的评论。也可以这样做:

$foo.parents().last().is(document.documentElement);

#7


0  

Why not just: if( $('#foo').length === 0)... ?

为什么不只是:if($('#foo'))。长度= = = 0)…吗?

#8


0  

if($foo.nodeType ){ element is node type}

#9


0  

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;
};

#10


0  

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

来源中数

Note:

注意:

#11


0  

instead of iterating parents you can just get the bounding rect which is all zeros when the element is detached from dom

不用迭代父元素,只需获得边界rect,该矩形在元素与dom分离时都是0

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

如果你想处理零宽度和高度元素在零和零的边界情况,你可以重复检查父母直到文件。

#1


216  

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

如果删除了其中一个元素的父元素(在这种情况下,元素本身仍然有父元素),这仍然有效。

#2


21  

How about doing this:

如何做:

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

#3


5  

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()。长度= = = 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.

[编辑:这不是完全正确的,因为删除的元素仍然可以有父元素;例如,如果您删除一个

    ,它的每个子
  • s仍然有一个父元素。使用SLaks回答。

  • 年代仍然有一个父元素。使用SLaks回答。

#4


4  

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,英语教学[0])。

#5


1  

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;
}

#6


0  

Agree with Perro's comment. It can also be done like this:

同意Perro的评论。也可以这样做:

$foo.parents().last().is(document.documentElement);

#7


0  

Why not just: if( $('#foo').length === 0)... ?

为什么不只是:if($('#foo'))。长度= = = 0)…吗?

#8


0  

if($foo.nodeType ){ element is node type}

#9


0  

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;
};

#10


0  

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

来源中数

Note:

注意:

#11


0  

instead of iterating parents you can just get the bounding rect which is all zeros when the element is detached from dom

不用迭代父元素,只需获得边界rect,该矩形在元素与dom分离时都是0

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

如果你想处理零宽度和高度元素在零和零的边界情况,你可以重复检查父母直到文件。