JAVASCRIPT
Determine if a DOM Element is Visually Rendered and Not Hidden
Learn how to programmatically check if a DOM element is currently visible on the page, accounting for `display: none`, `visibility: hidden`, and other factors.
function isElementVisible(element) {
if (!(element instanceof Element)) {
console.error("Provided argument is not a valid DOM element.");
return false;
}
// Check if element has an offset parent (implies it's in the document flow)
// and if its display style is not 'none'.
if (element.offsetParent === null) {
return false; // Not in the document flow or display: none
}
// Check computed styles for 'display' and 'visibility'
const computedStyle = getComputedStyle(element);
if (computedStyle.display === 'none' || computedStyle.visibility === 'hidden') {
return false;
}
// You might also consider opacity < 0.01 for practical invisibility
// if (parseFloat(computedStyle.opacity) < 0.01) {
// return false;
// }
return true;
}
// Example Usage:
// <div id="myDiv" style="display: block;">Visible Div</div>
// <span id="hiddenSpan" style="display: none;">Hidden Span</span>
// <p id="invisibleP" style="visibility: hidden;">Invisible Paragraph</p>
// console.log("Div visible:", isElementVisible(document.getElementById('myDiv'))); // true
// console.log("Span visible:", isElementVisible(document.getElementById('hiddenSpan'))); // false
// console.log("Paragraph visible:", isElementVisible(document.getElementById('invisibleP'))); // false
How it works: This function checks if a given DOM element is currently rendered and visually available on the page. It first checks `offsetParent`, which is `null` if the element itself or any of its ancestors has `display: none`. Then, it uses `getComputedStyle` to explicitly verify that `display` is not `none` and `visibility` is not `hidden`. This provides a robust way to determine an element's rendering status.