Home > Web Front-end > JS Tutorial > How Can I Determine Element Visibility in Pure JavaScript?

How Can I Determine Element Visibility in Pure JavaScript?

Patricia Arquette
Release: 2024-11-28 22:52:11
Original
636 people have browsed it

How Can I Determine Element Visibility in Pure JavaScript?

Determining Element Visibility in Pure JavaScript

In the absence of jQuery, developers often seek methods to ascertain whether an element is visible within the DOM. This article addresses this question, exploring various attributes that can indicate visibility or hidden status.

While examining the display attribute remains an important factor, it's not the only consideration. The visibility attribute can also affect visibility, indicating whether an element is currently hidden.

However, further attributes may also need attention. According to MDN documentation, an element's offsetParent property returns null when it or its parents are hidden via the display style. To determine visibility excluding fixed elements, the following script can be employed:

function isHidden(el) {
    return (el.offsetParent === null);
}
Copy after login

However, fixed elements may require a different approach, relying on window.getComputedStyle(). The following function takes such elements into account:

function isHidden(el) {
    var style = window.getComputedStyle(el);
    return (style.display === 'none');
}
Copy after login

While the second option is more comprehensive, it may be computationally slower. Hence, the optimal choice depends on the frequency of the operation.

The above is the detailed content of How Can I Determine Element Visibility in Pure 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