How to find with javascript if element exists in DOM or it's virtual (has been just created by createElement)

后端 未结 6 1556
庸人自扰
庸人自扰 2021-01-12 04:36

I\'m looking for a way to find if element referenced in javascript has been inserted in the document.

Lets illustrate a case with following code:

v         


        
6条回答
  •  难免孤独
    2021-01-12 04:55

    The safest way is to test directly whether the element is contained in the document:

    function isInDocument(el) {
        var html = document.body.parentNode;
        while (el) {
            if (el === html) {
                return true;
            }
            el = el.parentNode;
        }
        return false;
    }
    
    var elem = document.createElement('div');
    alert(isInDocument(elem));
    document.body.appendChild(elem);
    alert(isInDocument(elem));
    

提交回复
热议问题