如何在不使用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变量为什么会这样表现感兴趣。


当前回答

我喜欢这种方法:

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

其他回答

节点使用。包含DOM API,你可以检查页面中任何元素的存在(当前在DOM中)非常容易:

document.body.contains(YOUR_ELEMENT_HERE);

跨浏览器注意:Internet Explorer中的文档对象没有contains()方法——为了确保跨浏览器兼容性,请使用document.body.contains()代替。

// 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;
}

来自Mozilla开发者网络:

这个函数检查元素是否在页面主体中。由于contains()是包含的,而isInPage的目的不是确定正文是否包含自身,因此这种情况显式返回false。

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

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

我只是这样做:

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

这对我来说很有效,而且还没有任何问题……

jQuery的解决方案:

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

这为我使用jQuery工作,不需要$('#elementId')[0]被使用。