How to check if DOM reference has been destroyed?

时间:2015-06-25 19:06:04

标签: javascript dom

Say I select an element the old fashioned way (or any other way by which a DOM reference might be obtained): var el = document.getElementById('myFavoriteElement'); Then I remove that element's parent from the DOM, thus removing el as well. Or I just remove el directly. Is there a way to check whether el is still a valid reference, whether the HTML to which it refers still exists in the DOM? Something along the lines of el.hasBeenDestroyed as a boolean attribute, or something like that?

4 个答案:

答案 0 :(得分:3)

如果元素位于页面DOM上,则将填充baseURI属性。检查一下。

或者,尝试document.body.contains(node)

答案 1 :(得分:1)

以下是使用document.contains(el);的示例。

function removeSpan()
{
  var el = document.getElementById("test");
  el.parentNode.removeChild(el);
  document.getElementById("exist").innerHTML = document.contains(el);
}
<div>This is a div. <span id="test">This is a span</span></div>
<button type="button" onclick="removeSpan();">Remove span</button>
<div>Does the span exist? <span id="exist">true</span></div>

答案 2 :(得分:0)

您无法检查它是否已被销毁,但您可以检查它是否仍在文档节点中。

function inDocument(el) {
    var parentNode = el.parentNode;
    while (parentNode) {
        if (parentNode === document) {
            return true;
        }
        parentNode = parentNode.parentNode;
    }
    return false;
}

答案 3 :(得分:0)

只需寻找父母。

function hasBeenDestroyed(el){ return !el.parentNode; }

演示

var el = document.getElementById('myDiv');
document.getElementById('destroyBtn').onclick = function(){ el.outerHTML = ''; };
document.getElementById('checkBtn').onclick = function(){
    if( hasBeenDestroyed(el) ) alert('The div has been destroyed');
    else alert('The div is still here');
};

function hasBeenDestroyed(el){ return !el.parentNode; }
#myDiv{ padding: 1em; background: red; }
<button id="destroyBtn">Destroy the div</button>
<button id="checkBtn">Check if div still exists</button>

<div id="myDiv"></div>