如何检查可见 DOM 中是否存在元素? [英] How can I check if an element exists in the visible DOM?

查看:39
本文介绍了如何检查可见 DOM 中是否存在元素?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何在不使用 getElementById 方法的情况下测试元素是否存在?

我已经建立了一个现场演示以供参考.我也会在这里打印代码:

<头><脚本>var getRandomID = 函数(大小){var str = "",我 = 0,字符 = "0123456789abcdefghijklmnopqurstuvwxyzABCDEFGHIJKLMNOPQURSTUVWXYZ";而 (i <大小) {str += chars.substr(Math.floor(Math.random() * 62), 1);我++;}返回字符串;},isNull = 函数(元素){var randomID = getRandomID(12),已保存 ID = (element.id)?element.id:空;element.id = randomID;var foundElm = document.getElementById(randomID);element.removeAttribute('id');if (savedID !== null) {element.id = 保存的 ID;}返回(发现榆树)?假:真;};window.onload = 函数 () {var image = document.getElementById("demo");console.log('undefined', (typeof image === 'undefined') ? true : false);//错误的console.log('null', (image === null) ? true : false);//错误的console.log('find-by-id', isNull(image));//错误的image.parentNode.removeChild(image);console.log('undefined', (typeof image === 'undefined') ? true : false);//假~应该是真的?console.log('null', (image === null) ? true : false);//假~应该是真的?console.log('find-by-id', isNull(image));//true ~ 正确但一定有比这更好的方法吗?};<身体><div id="演示"></div>

基本上上面的代码演示了一个元素被存储到一个变量中,然后从 DOM 中删除.即使该元素已从 DOM 中移除,该变量仍会保留该元素最初声明时的状态.换句话说,它不是对元素本身的实时引用,而是一个副本.因此,检查变量的值(元素)是否存在将提供意想不到的结果.

isNull 函数是我尝试从变量中检查元素是否存在的尝试,并且它有效,但我想知道是否有更简单的方法来实现相同的结果.

PS:如果有人知道一些与该主题相关的好文章,我也对为什么 JavaScript 变量的行为如此感兴趣.

解决方案

似乎有些人在这里登陆,只是想知道一个元素是否存在(与最初的问题有点不同).

这就像使用任何浏览器的选择方法一样简单,并检查它的真实值(通常).

例如,如果我的元素有一个 "find-me"id,我可以简单地使用...

var elementExists = document.getElementById("find-me");

这被指定为返回对元素的引用或null.如果你必须有一个布尔值,只需在方法调用前扔一个 !! 即可.

此外,您可以使用现有的许多其他方法中的一些来查找元素,例如 (all living off document):

  • querySelector()/querySelectorAll()
  • getElementsByClassName()
  • getElementsByName()

其中一些方法返回一个 NodeList,所以一定要检查它的 length 属性,因为 NodeList 是一个对象,因此真实.

<小时>

为了实际确定元素是否作为可见 DOM 的一部分存在(如最初提出的问题),Csuwldcat 提供了比滚动你自己的更好的解决方案(因为这个答案曾经包含).也就是说,要使用 contains() DOM 元素的方法.

你可以像这样使用它...

document.body.contains(someReferenceToADomElement);

How do you test an element for existence without the use of the getElementById method?

I have set up a live demo for 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.

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.

PS: I'm also interested in why JavaScript variables behave like this if anyone knows of some good articles related to the subject.

解决方案

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

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.

In addition, you can use some of the many other methods that exist for finding elements, such as (all living off document):

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


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.

You could use it like so...

document.body.contains(someReferenceToADomElement);

这篇关于如何检查可见 DOM 中是否存在元素?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆