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


当前回答

这种情况适用于所有情况。

函数del() { 如果dom中有这个元素,则返回小鸡 //if not true condition表示null或unfind或false。 如果(!文档。querySelector (" # ul_list ") = = = true) { // MSG给用户 警报(“点击BTN加载”); //如果控制台小鸡为你和显示null清除控制台。 console.clear (); //函数停止。 返回错误; } //如果它的true函数将日志删除。 console.log(“删除”); }

其他回答

您可以检查parentNode属性是否为空。

也就是说,

if(!myElement.parentNode)
{
    // The node is NOT in the DOM
}
else
{
    // The element is in the DOM
}

而不是迭代父元素,当元素从DOM中分离出来时,你可以得到一个全为0的边界矩形:

function isInDOM(element) {
    if (!element)
        return false;
    var rect = element.getBoundingClientRect();
    return (rect.top || rect.left || rect.height || rect.width)?true:false;
}

如果你想处理宽度和高度都为零的元素的边缘情况,你可以通过迭代父元素直到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;
}
// 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;
}

使用下面的命令返回元素是否存在于DOM中:

return !!document.getElementById('myElement');

我只是这样做:

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

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