Home >Web Front-end >JS Tutorial >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!