'How to check if DOM reference has been destroyed? [duplicate]
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?
Solution 1:[1]
The baseURI attribute will be filled in if the element is on the page DOM. Check that.
Alternatively, try document.body.contains(node).
Edit: Now in 2022, the DOM node isConnected readonly property provides this information. My experiment shows that the baseURI property remains filled even when removed from the DOM.
Solution 2:[2]
Here is an example using 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>
Solution 3:[3]
Simply look for a parent.
function hasBeenDestroyed(el){ return !el.parentNode; }
Demo
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>
Solution 4:[4]
You cannot check whether it has been destroyed, but you can check whether it is still in the document node.
function inDocument(el) {
var parentNode = el.parentNode;
while (parentNode) {
if (parentNode === document) {
return true;
}
parentNode = parentNode.parentNode;
}
return false;
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Stephen Isienyi |
| Solution 2 | imtheman |
| Solution 3 | |
| Solution 4 |
