Home > Web Front-end > JS Tutorial > How Can I Check DOM Element Visibility in Plain JavaScript?

How Can I Check DOM Element Visibility in Plain JavaScript?

Linda Hamilton
Release: 2024-11-29 03:03:17
Original
613 people have browsed it

How Can I Check DOM Element Visibility in Plain JavaScript?

Checking Element Visibility in the DOM

Question:

Can we determine if an element is visible in the DOM using JavaScript without relying on external libraries like jQuery? If so, which attributes should we consider to ensure accurate visibility checks?

Answer:

To check element visibility in pure JavaScript, consider the following attributes:

  • display: Elements with a "display" style of "none" are considered hidden.
  • visibility: Hidden elements have a "visibility" style of "hidden."

To check if an element is visible, you can use the following code:

function isElementVisible(element) {
  // Check if the element has any parent with "display: none"
  if (element.offsetParent === null) {
    return false;
  }

  // Check if the element itself has "display: none" or "visibility: hidden"
  const style = window.getComputedStyle(element);
  return style.display !== "none" && style.visibility !== "hidden";
}
Copy after login

This approach works for most cases. However, if your page contains elements with "position: fixed", you may need to use a more comprehensive approach that also checks for elements outside the normal document flow. In such cases, you can use the following:

function isElementVisibleFixed(element) {
  // Check if the element has any parent with "display: none"
  if (element.offsetParent === null) {
    return false;
  }

  // Check if the element itself has "display: none" or "visibility: hidden" or "position: fixed"
  const style = window.getComputedStyle(element);
  return style.display !== "none" && style.visibility !== "hidden" && style.position !== "fixed";
}
Copy after login

The above is the detailed content of How Can I Check DOM Element Visibility in Plain JavaScript?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
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