"If a worker wants to do his job well, he must first sharpen his tools." - Confucius, "The Analects of Confucius. Lu Linggong"
Front page > Programming > How to Get the Height of Hidden Elements in jQuery Efficiently?

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

Published on 2024-11-05
Browse:227

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:

$select.show();
optionHeight = $firstOption.height(); // Obtain height after displaying the element
$select.hide();

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:

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 : "");
Latest tutorial More>

Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.

Copyright© 2022 湘ICP备2022001581号-3