Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Check if a DOM element node actually exists in DOM

I’m defining a function that should receive a DOM element node as a parameter.

There is any efficient way to validate if the element node received actually exists in the DOM?

For example if the element node received has been created through Document.createElement() but not appended to the DOM, I want the validation fails.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

I already accomplished it with the code below, but I’m afraid that checking for all DOM element nodes is not the best solution for performance.

function checkIfNodeExists(nodeElement) {
  return [...document.querySelectorAll("*")].includes(nodeElement);
}

Could someone suggest a better solution or convince me that my solution is already appropriate?

>Solution :

You want to check if an element is in the DOM? You can see if it is in the body.

var div1 = document.createElement("div");
var div2 = document.querySelector("#foo");


console.log(document.body.contains(div1))
console.log(document.body.contains(div2))
<div id="foo"><div>
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading