JQuery:检查元素是否与“.remove()”一起存在

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6714198/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 21:17:02  来源:igfitidea点击:

JQuery: Check if element exists alongside '.remove()'

jqueryexists

提问by gavsiu

I know you can check if an element exists with $('div').length, but when an element is destroyed using .remove(), .lengthstill reports the div exists. How can I find whether or not it actually exists?

我知道您可以使用 来检查元素是否存在$('div').length,但是当使用 销毁元素时.remove().length仍然报告 div 存在。我怎样才能知道它是否真的存在?

if ($('div').length) { 
  alert('yes') 
} else { 
  alert('no') 
}

采纳答案by Felix Kling

Test whether it has a parent:

测试它是否有父级:

if ($element.parent().length) { alert('yes') }
else { alert('no') }

or if you have a reference to the DOM element:

或者如果您有对 DOM 元素的引用:

if(element.parentNode) {
    // yes
}

Obviously, this only works for elements you already have a reference to.

显然,这仅适用于您已经引用的元素。

FWIW, the element itself still exists, it is just not part of the DOM tree.

FWIW,元素本身仍然存在,它只是不是 DOM 树的一部分。

回答by gilly3

By exists, you mean you want to see if it exists in the dom? Check to see if "html" is an ancestor:

存在,你的意思是你想看看它是否存在于dom中?检查“html”是否是祖先:

var $myDiv = $(".myDiv");
$myDiv.closest("html").length;  // returns 1
$myDiv.remove();
$myDiv.closest("html").length;  // returns 0

Or use .is("html *"). It returns a boolean, which is handy:

或使用.is("html *"). 它返回一个布尔值,这很方便:

var $myDiv = $(".myDiv");
$myDiv.is("html *"); // returns true
$myDiv.remove();
$myDiv.is("html *"); // returns false

回答by user1444978

if (!$foo.closest('html').length) {
    //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).

if (!$foo.closest('html').length) {
    //Element is detached
}

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

I cite this answer.

我引用这个答案

回答by Ehtesham

you can get the parent of element before removing the element and after the element has been removed you can check like this!

您可以在删除元素之前获取元素的父级,并且在删除元素之后您可以像这样检查!

    var parent = $(element).parent();
    $(element).remove();

    if(parent.children(element)) {  alert('yes'); }
    else { alert('no'); }

of course element would be some jquery selector

当然元素将是一些jquery选择器