Question:
Can we determine if an element is visible within the DOM without relying on jQuery? Specifically, which attributes should we check to ascertain its visibility?
Answer:
According to MDN documentation, an element's offsetParent property returns null if it or any of its ancestors are hidden via the display style property. However, this assumes that the element is not positioned fixed. If no position: fixed elements are present on the page, a concise script to check visibility could be:
function isHidden(el) { return (el.offsetParent === null); }
If there are position: fixed elements on the page, however, we regrettably have to resort to window.getComputedStyle() for a thorough check, which may have performance implications:
function isHidden(el) { var style = window.getComputedStyle(el); return (style.display === 'none'); }
Despite its susceptibility to edge cases, the second option offers greater clarity. If the operation is to be performed repeatedly, consider the first option for efficiency, avoiding the performance penalties of window.getComputedStyle().
The above is the detailed content of How Can I Determine Element Visibility in the DOM Using Only JavaScript?. For more information, please follow other related articles on the PHP Chinese website!