如何在不使用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>

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

isNull函数是我试图从变量中检查元素的存在,它可以工作,但我想知道是否有更简单的方法来实现相同的结果。

PS:如果有人知道一些与这个主题相关的好文章,我还对JavaScript变量为什么会这样表现感兴趣。


当前回答

检查元素是否存在

const elementExists = document.getElementById("find-me");
if(elementExists){
    console.log("have this element");
}else{
    console.log("this element doesn't exist");
}

其他回答

我喜欢这种方法:

var elem = document.getElementById('elementID');

if (elem)
    do this
else
    do that

Also

var elem = ((document.getElementById('elemID')) ? true:false);

if (elem)
    do this
else
    do that

通过jQuery的一行代码,可以简单地检查元素是否存在。

下面是代码:

if ($('#elementId').length > 0) {
    // Do stuff here if the element exists
} else {
    // Do stuff here if the element does not exist
}

这段代码适合我,我没有遇到任何问题。


    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");
    }

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

const div = document.createElement('div'); console.log ( document.documentElement.contains (div) ); / / - >错误的 document.body.appendChild (div); console.log ( document.documentElement.contains (div) ); / / - - - - - - >正确的

我在is-dom-detached中已经讲过了。

// This will work prefectly in all :D
function basedInDocument(el) {

    // This function is used for checking if this element in the real DOM
    while (el.parentElement != null) {
        if (el.parentElement == document.body) {
            return true;
        }
        el = el.parentElement; // For checking the parent of.
    } // If the loop breaks, it will return false, meaning
      // the element is not in the real DOM.

    return false;
}