Home > Web Front-end > JS Tutorial > body text

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

Linda Hamilton
Release: 2024-10-21 22:27:02
Original
674 people have browsed it

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>
Copy after login

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>
Copy after login

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!

source:php
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!