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 truthy value (generally).
(这就像使用任何浏览器的选择方法一样简单,并检查它的真实值(通常)。)
For example, if my element had an id
of "find-me"
, I could simply use...
(例如,如果我的元素的id
为"find-me"
,我可以简单地使用...)
var elementExists = document.getElementById("find-me");
This is spec'd to either return a reference to the element or null
.
(这被指定要么返回对元素的引用,要么返回null
。)
If you must have a Boolean value, simply toss a !!
(如果你必须有一个布尔值,只需扔一个!!
)
before the method call. (在方法调用之前。)
In addition, you can use some of the many other methods that exist for finding elements, such as (all living off document
):
(此外,您可以使用其他许多方法来查找元素,例如(所有生活在document
):)
Some of these methods return a NodeList
, so be sure to check its length
property, because a NodeList
is an object, and therefore truthy .
(其中一些方法返回一个NodeList
,因此请务必检查其length
属性,因为NodeList
是一个对象,因此是真实的 。)
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).
(为了实际确定一个元素是否作为可见DOM的一部分存在(如最初提出的问题), Csuwldcat提供了一个比滚动自己更好的解决方案 (如此答案所包含)。)
That is, to use the contains()
method on DOM elements. (也就是说,在DOM元素上使用contains()
方法。)
You could use it like so...
(你可以像这样使用它......)
document.body.contains(someReferenceToADomElement);