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
Patricia ArquetteOriginal
2024-11-28 22:52:11680browse

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);
}

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

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!

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