Home  >  Article  >  Web Front-end  >  How to Efficiently Check Element Existence in the Visible DOM Without Using getElementById?

How to Efficiently Check Element Existence in the Visible DOM Without Using getElementById?

Linda Hamilton
Linda HamiltonOriginal
2024-10-21 22:27:02675browse

How to Efficiently Check Element Existence in the Visible DOM Without Using getElementById?

How to Check Element Existence in the Visible DOM

Testing for Element Existence Without getElementById

When attempting to verify element existence without using getElementById, it becomes apparent that variables do not maintain live references to DOM elements but instead retain their initial values. This can lead to unexpected results when checking an element's existence after its removal from the DOM.

A Method for Checking Existence

To address this issue, consider the isNull function, which attempts to ascertain an element's existence:

<code class="javascript">var isNull = function (element) {
  var randomID = getRandomID(12),
    savedID = (element.id) ? element.id : null;
  element.id = randomID;
  var foundElm = document.getElementById(randomID);
  element.removeAttribute('id');
  if (savedID !== null) {
    element.id = savedID;
  }
  return (foundElm) ? false : true;
};</code>

This method works, but an easier approach is suggested.

Checking Existence in the Visible DOM

To determine if an element is present within the visible DOM, utilize the contains() method:

<code class="javascript">document.body.contains(someReferenceToADomElement);</code>

This method returns a Boolean indicating whether the element is part of the DOM. It offers a more direct and efficient way to check existence compared to the isNull function.

The above is the detailed content of How to Efficiently Check Element Existence in the Visible DOM Without Using getElementById?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn