Q:

Check whether element from variable has a refference in current DOM

Assume I have an element in a variable:
var element = document.getElementsByTagName("div")[0] 
// here can be any kind of getting element, e. g. React ref, Chrome's devtools $0, etc.

At some point of time my markup is changing (like in SPA), and element from variable has been removed from DOM, but it still available in the element with all properties, such as parentElement, etc.
The question is: how to check, if my DOM element from element is present in DOM?
I tried to check the element.getBoundingClientRect(), and yes, there are some differences: element that removed from DOM has all the zeroes in his bounding rect. But there is one thing: element with display: none also has all the zeroes in its bounding rect, despite of it is still presents in the DOM (physically, lets say). This is not acceptable in my case, because I need to differ hidden element from removed element.

A:

You can use contains for this purpose

function contains() {
  const result = document.body.contains(element);
  console.log(result);
}

const element = document.getElementById('app');
contains();

element.classList.add('hide');
contains();

element.parentNode.removeChild(element);
contains();
.hide {
  display: none;
}
<div id="app">App</div>

