Home >Web Front-end >JS Tutorial >How to Get the Height of Hidden Elements in jQuery Efficiently?

How to Get the Height of Hidden Elements in jQuery Efficiently?

Susan Sarandon
Susan SarandonOriginal
2024-11-03 14:00:03634browse

How to Get the Height of Hidden Elements in jQuery Efficiently?

Getting Height of Hidden Elements in jQuery

When dealing with hidden elements, retrieving their height can be challenging. The conventional approach of temporarily displaying the element to measure its height and then hiding it again seems inefficient. Is there a more optimal solution?

jQuery 1.4.2 Approach

Here's an example using jQuery 1.4.2:

<code class="js">$select.show();
optionHeight = $firstOption.height(); // Obtain height after displaying the element
$select.hide();</code>

This method has the disadvantage of changing the element's visibility, which may cause unwanted side effects.

Hacking the Element's Style

An alternative approach is to manipulate the element's style to make it invisible while calculating its height:

<code class="js">var previousCss = $("#myDiv").attr("style"); // Store the original style

// Set visibility to 'hidden' and display to 'block'
$("#myDiv").css({
    position: 'absolute', // Optional if the element is already absolute
    visibility: 'hidden',
    display: 'block'
});

optionHeight = $("#myDiv").height(); // Measure height with modified visibility

// Restore the original style
$("#myDiv").attr("style", previousCss ? previousCss : "");</code>

The above is the detailed content of How to Get the Height of Hidden Elements in jQuery Efficiently?. 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