How to check if the DOM link has been destroyed?

Let's say I select an element in the old-fashioned way (or in any other way with which to get the DOM link):

var el = document.getElementById('myFavoriteElement'); 

Then I remove the parent from the DOM, thereby removing el . Or just delete el directly.

Is there a way to check if el is still a valid link, is the HTML it refers to still exist in the DOM? Something along the lines of el.hasBeenDestroyed as a boolean attribute or something like that?

+6
source share
4 answers

The baseURI attribute will be populated if the item is on the DOM page. Check this.

Alternatively try document.body.contains(node) .

+3
source

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> 
+1
source

You cannot check if it has been destroyed, but you can check if it is all in the node document.

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

Just find 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> 
0
source

Source: https://habr.com/ru/post/989763/


All Articles