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:
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!