-1

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.

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?

Bernat
  • 825
  • 1
  • 6
  • 10
  • 1
    Another similar question that might be helpful: [How can I tell if a node is in memory or in the dom?](https://stackoverflow.com/questions/11943441/how-can-i-tell-if-a-node-is-in-memory-or-in-the-dom) - see [this answer](https://stackoverflow.com/a/63794198/14956277) for [`Node.isConnected`](https://developer.mozilla.org/en-US/docs/Web/API/Node/isConnected) – D M Jun 21 '22 at 15:37

1 Answers1

0

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>
epascarello
  • 204,599
  • 20
  • 195
  • 236