Javascript 如何检查可见 DOM 中是否存在元素?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5629684/
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 can I check if an element exists in the visible DOM?
提问by Justin Bull
How do you test an element for existence without the use of the getElementById
method?
如何在不使用该getElementById
方法的情况下测试元素是否存在?
I have set up a live demofor reference. I will also print the code on here as well:
我已经设置了一个现场演示以供参考。我也会在这里打印代码:
<!DOCTYPE html>
<html>
<head>
<script>
var getRandomID = function (size) {
var str = "",
i = 0,
chars = "0123456789abcdefghijklmnopqurstuvwxyzABCDEFGHIJKLMNOPQURSTUVWXYZ";
while (i < size) {
str += chars.substr(Math.floor(Math.random() * 62), 1);
i++;
}
return str;
},
isNull = function (element) {
var randomID = getRandomID(12),
savedID = (element.id)? element.id : null;
element.id = randomID;
var foundElm = document.getElementById(randomID);
element.removeAttribute('id');
if (savedID !== null) {
element.id = savedID;
}
return (foundElm) ? false : true;
};
window.onload = function () {
var image = document.getElementById("demo");
console.log('undefined', (typeof image === 'undefined') ? true : false); // false
console.log('null', (image === null) ? true : false); // false
console.log('find-by-id', isNull(image)); // false
image.parentNode.removeChild(image);
console.log('undefined', (typeof image === 'undefined') ? true : false); // false ~ should be true?
console.log('null', (image === null) ? true : false); // false ~ should be true?
console.log('find-by-id', isNull(image)); // true ~ correct but there must be a better way than this?
};
</script>
</head>
<body>
<div id="demo"></div>
</body>
</html>
Basically the above code demonstrates an element being stored into a variable and then removed from the DOM. Even though the element has been removed from the DOM, the variable retains the element as it was when first declared. In other words, it is not a live reference to the element itself, but rather a replica. As a result, checking the variable's value (the element) for existence will provide an unexpected result.
基本上上面的代码演示了一个元素被存储到一个变量中,然后从 DOM 中删除。即使该元素已从 DOM 中移除,该变量仍会保留该元素最初声明时的状态。换句话说,它不是对元素本身的实时引用,而是一个副本。因此,检查变量的值(元素)是否存在将提供意想不到的结果。
The isNull
function is my attempt to check for an elements existence from a variable, and it works, but I would like to know if there is an easier way to accomplish the same result.
该isNull
函数是我尝试从变量中检查元素是否存在,并且它有效,但我想知道是否有更简单的方法来完成相同的结果。
PS: I'm also interested in why JavaScript variables behave like this if anyone knows of some good articles related to the subject.
PS:如果有人知道一些与该主题相关的好文章,我也对为什么 JavaScript 变量的行为如此感兴趣。
回答by alex
It seems some people are landing here, and simply want to know if an element exists(a little bit different to the original question).
似乎有些人在这里登陆,只是想知道一个元素是否存在(与原始问题有点不同)。
That's as simple as using any of the browser's selecting method, and checking it for a truthyvalue (generally).
这就像使用任何浏览器的选择方法一样简单,并检查它的真值(通常)。
For example, if my element had an id
of "find-me"
, I could simply use...
例如,如果我的元素有一个id
of "find-me"
,我可以简单地使用...
var elementExists = document.getElementById("find-me");
This is specified to either return a reference to the element or null
. If you must have a Boolean value, simply toss a !!
before the method call.
这被指定为返回对元素的引用或null
. 如果你必须有一个布尔值,只需!!
在方法调用之前扔一个。
In addition, you can use some of the many other methods that exist for finding elements, such as (all living off document
):
此外,您可以使用现有的许多其他方法来查找元素,例如(all living off document
):
querySelector()
/querySelectorAll()
getElementsByClassName()
getElementsByName()
querySelector()
/querySelectorAll()
getElementsByClassName()
getElementsByName()
Some of these methods return a NodeList
, so be sure to check its length
property, because a NodeList
is an object, and therefore truthy.
其中一些方法返回 a NodeList
,所以一定要检查它的length
属性,因为 aNodeList
是一个对象,因此是真实的。
For actually determining if an element exists as part of the visible DOM (like the question originally asked), Csuwldcat provides a better solution than rolling your own(as this answer used to contain). That is, to use the contains()
method on DOM elements.
为了实际确定一个元素是否作为可见 DOM 的一部分存在(就像最初提出的问题),Csuwldcat 提供了比滚动你自己的更好的解决方案(因为这个答案曾经包含)。也就是说,在 DOM 元素上使用该contains()
方法。
You could use it like so...
你可以像这样使用它...
document.body.contains(someReferenceToADomElement);
回答by Kon
Use getElementById()
if it's available.
使用getElementById()
如果它是可用的。
Also, here's an easy way to do it with jQuery:
此外,这里有一个简单的方法来使用 jQuery:
if ($('#elementId').length > 0) {
// Exists.
}
And if you can't use third-party libraries, just stick to base JavaScript:
如果你不能使用第三方库,就坚持使用基础 JavaScript:
var element = document.getElementById('elementId');
if (typeof(element) != 'undefined' && element != null)
{
// Exists.
}
回答by csuwldcat
Using the Node.contains DOM API, you can check for the presence of any element in the page (currently in the DOM) quite easily:
使用Node.contains DOM API,您可以非常轻松地检查页面中(当前在 DOM 中)是否存在任何元素:
document.body.contains(YOUR_ELEMENT_HERE);
CROSS-BROWSER NOTE: the document
object in Internet Explorer does not have a contains()
method - to ensure cross-browser compatibility, use document.body.contains()
instead.
CROSS-BROWSER 注意:document
Internet Explorer 中的对象没有contains()
方法 - 为确保跨浏览器兼容性,请document.body.contains()
改用。
回答by Anomaly
I simply do:
我只是这样做:
if(document.getElementById("myElementId")){
alert("Element exists");
} else {
alert("Element does not exist");
}
It works for me and had no issues with it yet...
它对我有用,而且还没有问题......
回答by Ekramul Hoque
From Mozilla Developer Network:
This function checks to see if an element is in the page's body. As contains() is inclusive and determining if the body contains itself isn't the intention of isInPage, this case explicitly returns false.
这个函数检查一个元素是否在页面的正文中。由于 contains() 是包含性的,并且确定正文是否包含自身不是 isInPage 的意图,因此这种情况显式返回 false。
function isInPage(node) {
return (node === document.body) ? false : document.body.contains(node);
}
nodeis the node we want to check for in the <body>.
node是我们要在 <body> 中检查的节点。
回答by mikechambers
You could just check to see if the parentNode property is null.
您可以只检查 parentNode 属性是否为空。
That is,
那是,
if(!myElement.parentNode)
{
// The node is NOT in the DOM
}
else
{
// The element is in the DOM
}
回答by mikechambers
The easiest solution is to check the baseURIproperty, which is set only when the element is inserted in the DOM, and it reverts to an empty string when it is removed.
最简单的解决方案是检查baseURI属性,该属性仅在元素插入 DOM 时设置,并在删除时恢复为空字符串。
var div = document.querySelector('div');
// "div" is in the DOM, so should print a string
console.log(div.baseURI);
// Remove "div" from the DOM
document.body.removeChild(div);
// Should print an empty string
console.log(div.baseURI);
<div></div>
回答by Code Buster
jQuery solution:
jQuery 解决方案:
if ($('#elementId').length) {
// element exists, do something...
}
This worked for me using jQuery and did not require $('#elementId')[0]
to be used.
这对我使用 jQuery 有效,不需要$('#elementId')[0]
使用。
回答by DoctorDestructo
csuwldcat's solutionseems to be the best of the bunch, but a slight modification is needed to make it work correctly with an element that's in a different document than the JavaScript code is running in, such as an iframe:
csuwldcat 的解决方案似乎是最好的解决方案,但需要稍作修改才能使其与运行 JavaScript 代码所在文档不同的元素(例如 iframe)正常工作:
YOUR_ELEMENT.ownerDocument.body.contains(YOUR_ELEMENT);
Note the use of the element's ownerDocument
property, as opposed to just plain old document
(which may or may not refer to the element's owner document).
请注意元素ownerDocument
属性的使用,而不是简单的旧属性document
(可能引用也可能不引用元素的所有者文档)。
torazaburo posted an even simpler methodthat also works with non-local elements, but unfortunately, it uses the baseURI
property, which is not uniformly implemented across browsers at this time (I could only get it to work in the WebKit-based ones). I couldn't find any other element or node properties that could be used in a similar fashion, so I think for the time being the above solution is as good as it gets.
torazaburo 发布了一个更简单的方法,它也适用于非本地元素,但不幸的是,它使用了这个baseURI
属性,目前在浏览器中没有统一实现(我只能让它在基于 WebKit的浏览器中工作)。我找不到可以以类似方式使用的任何其他元素或节点属性,所以我认为目前上述解决方案已经足够了。
回答by Erez Pilosof
Instead of iterating parents, you can just get the bounding rectangle which is all zeros when the element is detached from the DOM:
当元素从 DOM 分离时,您可以只获得全零的边界矩形,而不是迭代父项:
function isInDOM(element) {
if (!element)
return false;
var rect = element.getBoundingClientRect();
return (rect.top || rect.left || 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
:
function isInDOM(element) {
if (!element)
return false;
var rect = element.getBoundingClientRect();
if (element.top || element.left || element.height || element.width)
return true;
while(element) {
if (element == document.body)
return true;
element = element.parentNode;
}
return false;
}