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
Linda HamiltonOriginal
2024-11-29 03:03:17664browse

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";
}

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";
}

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!

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