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

本文翻译自:How to check if element exists in the visible DOM?

How do you test an element for existence without the use of the getElementById method? 如何在不使用getElementById方法的情况下测试元素是否存在? I have setup 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 what the above code demonstrates is an element being stored into a variable and then removed from dom. 基本上上面代码演示的是一个元素存储到变量中然后从dom中删除。 Even though the element has been removed from the dom, the variable retains the element as it was when first declared. 即使元素已从dom中删除,该变量仍保留元素,就像第一次声明时一样。 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. 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变量的行为感兴趣。


#1楼

参考:https://stackoom.com/question/NcXM/如何检查可见DOM中是否存在元素


#2楼

使用jQuery的简单解决方案

$('body').find(yourElement)[0] != null

#3楼

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]用,并且不需要使用$('#elementId')[0]


#4楼

I simply do: 我只是这样做:

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

Works for me and had no issues with it yet.... 适合我,并没有任何问题....


#5楼

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 IE does not have a contains() method - to ensure cross-browser compatibility, use document.body.contains() instead CROSS-BROWSER注意 :IE中的document对象没有contains()方法 - 为了确保跨浏览器兼容性,请使用document.body.contains()代替


#6楼

From Mozilla Developer Network 来自Mozilla开发者网络

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. 由于包含是包容性的并且确定主体是否包含自身不是isInPage的意图,这种情况显式返回false。

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

node is the node we want to check for in the . node是我们要在中检查的节点。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值