How to check if element exists in the visible DOM?

2019-01-01 16:57发布

How do you test an element for existence without the use of the getElementById method? 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. 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.

17条回答
宁负流年不负卿
2楼-- · 2019-01-01 17:17

A simple way to check if element exist can be done through one-line code of jQuery.

Here is the code below:

if ($('#elementId').length > 0) {
    // do stuff here if element exists
}else {
    // do stuff here if element not exists
}
查看更多
美炸的是我
3楼-- · 2019-01-01 17:19

instead of iterating parents you can just get the bounding rect which is all zeros when the element is detached from 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

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;
}
查看更多
旧人旧事旧时光
4楼-- · 2019-01-01 17:19

Another option element.closest:

element.closest('body') === null
查看更多
步步皆殇っ
5楼-- · 2019-01-01 17:20

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.

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

node is the node we want to check for in the .

查看更多
无色无味的生活
6楼-- · 2019-01-01 17:20

Simple solution with jQuery

$('body').find(yourElement)[0] != null
查看更多
呛了眼睛熬了心
7楼-- · 2019-01-01 17:23

Easiest solution is to check the baseURI property, which is set only when the element is inserted in the DOM, and reverts to an empty string when it is removed.

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>

查看更多
登录 后发表回答