0

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.

1 Answer 1

2

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>

Sign up to request clarification or add additional context in comments.

1 Comment

God bless you! Thanks a lot :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.