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:31

Using the Node.contains DOM API, you can check for the presence of any element in the page (currently in the DOM) quite easily:

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

查看更多
浅入江南
3楼-- · 2019-01-01 17:33

Use this:

var isInDOM = function(element, inBody) {
    var _ = element, last;

    while (_) {
        last = _;
        if (inBody && last === document.body) { break;}
        _ = _.parentNode;
    }

    return inBody ? last === document.body : last === document;
};
查看更多
倾城一夜雪
4楼-- · 2019-01-01 17:34

Why would you not use getElementById() if it's available?

Also, here's an easy way to do it with jQuery:

if ($('#elementId').length > 0) {
  // exists.
}

And if you can't use 3rd-party libraries, just stick to base JavaScript:

var element =  document.getElementById('elementId');
if (typeof(element) != 'undefined' && element != null)
{
  // exists.
}
查看更多
公子世无双
5楼-- · 2019-01-01 17:38

Could you just check to see if the parentNode property is null?

i.e.

if(!myElement.parentNode)
{
    //node is NOT on the dom
}
else
{
    //element is on the dom
}
查看更多
爱死公子算了
6楼-- · 2019-01-01 17:39

jQuery solution:

if ($('#elementId').length) {
    // element exists, do something...
}

This worked for me using jQuery and did not require $('#elementId')[0] to be used.

查看更多
登录 后发表回答