如何检查可见DOM中是否存在元素?

JavaScript

达蒙Davaid斯丁

2020-04-03

不使用该getElementById方法如何测试元素的存在

我已经建立了一个现场演示供参考。我也将在此处打印代码:

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

第3963篇《如何检查可见DOM中是否存在元素?》来自Winter(https://github.com/aiyld/aiyld.github.io)的站点

11个回答
乐米亚 2020.04.03

该代码对我有用,我对此没有任何问题。


    if(document.getElementById("mySPAN")) {
        // If the element exists, execute this code
        alert("Element exists");
    }
    else {
        // If the element does not exist execute this code
        alert("Element does not exists");
    }

斯丁前端 2020.04.03

检查元素是否为<html>via 的子元素Node::contains()

const div = document.createElement('div');
document.documentElement.contains(div); //-> false

document.body.appendChild(div);
document.documentElement.contains(div); //-> true

我已经在is-dom-detach对此进行了介绍

伽罗卡卡西猴子 2020.04.03

不必迭代父对象,只需将元素从DOM分离出来,就可以得到全部为零的边界矩形:

function isInDOM(element) {
    if (!element)
        return false;
    var rect = element.getBoundingClientRect();
    return (rect.top || rect.left || rect.height || rect.width)?true:false;
}

如果要处理零宽和高元素在零顶部和左零处的边缘情况,则可以通过迭代父级直到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;
}
番长 2020.04.03

csuwldcat的解决方案似乎是最好的解决方案,但是需要稍作修改以使其与运行JavaScript代码所在的文档不在同一文档中的元素(例如iframe)正常工作:

YOUR_ELEMENT.ownerDocument.body.contains(YOUR_ELEMENT);

注意元素的ownerDocument属性的使用,而不是普通的旧的document(可能引用或可能不引用元素的所有者文档)。

torazaburo发布了一个甚至更简单的方法,该方法也可以用于非本地元素,但是不幸的是,它使用的baseURI属性,目前在浏览器之间并没有统一实现(我只能在基于WebKit浏览器中使用它)。我找不到可以类似方式使用的任何其他元素或节点属性,因此我暂时认为上述解决方案是可行的。

宝儿理查德 2020.04.03

您还可以使用jQuery.contains,它检查一个元素是否是另一个元素的后代。document作为搜索的父元素传入,因为页面DOM上存在的任何元素都是的后代document

jQuery.contains( document, YOUR_ELEMENT)
泡芙神无 2020.04.03

最简单的解决方案是检查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>

西里Near 2020.04.03

来自Mozilla开发人员网络

此函数检查元素是否在页面的正文中。因为contains()是包含性的,并且确定主体是否包含自身不是isInPage的意图,所以此例显式返回false。

function isInPage(node) {
  return (node === document.body) ? false : document.body.contains(node);
}

node是我们要在<body>中检查的节点。

2020.04.03

您可以检查一下parentNode属性是否为null。

那是,

if(!myElement.parentNode)
{
    // The node is NOT in the DOM
}
else
{
    // The element is in the DOM
}
乐米亚 2020.04.03

我只是做:

if(document.getElementById("myElementId")){
    alert("Element exists");
} else {
    alert("Element does not exist");
}

它对我有用,但还没有问题...

DavaidTony宝儿 2020.04.03

使用Node.contains DOM API,您可以很容易地检查页面中是否存在任何元素(当前在DOM中):

document.body.contains(YOUR_ELEMENT_HERE);

跨浏览器注意documentInternet Explorer中对象没有contains()方法-为确保跨浏览器兼容性,请document.body.contains()改用。

LGil 2020.04.03

似乎有些人在这里着陆,只是想知道某个元素是否存在(与原始问题略有不同)。

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

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

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

可以指定返回元素或的引用null如果必须具有布尔值,则只需!!在方法调用之前扔一个

此外,您可以使用许多其他方法来查找元素,例如(全部靠document):

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

其中一些方法返回a NodeList,因此请务必检查其length属性,因为a NodeList是一个对象,因此为true


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

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

document.body.contains(someReferenceToADomElement);

问题类别

JavaScript Ckeditor Python Webpack TypeScript Vue.js React.js ExpressJS KoaJS CSS Node.js HTML Django 单元测试 PHP Asp.net jQuery Bootstrap IOS Android