Home > Web Front-end > JS Tutorial > How Can I Determine Element Visibility in the DOM Using Only JavaScript?

How Can I Determine Element Visibility in the DOM Using Only JavaScript?

Barbara Streisand
Release: 2024-11-27 22:27:12
Original
860 people have browsed it

How Can I Determine Element Visibility in the DOM Using Only JavaScript?

Determining Element Visibility in the DOM Using Pure JavaScript

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);
}
Copy after login

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');
}
Copy after login

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!

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