Home  >  Article  >  Web Front-end  >  How to Get the Height of a Hidden Element with jQuery?

How to Get the Height of a Hidden Element with jQuery?

Barbara Streisand
Barbara StreisandOriginal
2024-11-02 19:47:021052browse

How to Get the Height of a Hidden Element with jQuery?

Retrieving Height of Concealed Elements with jQuery

When working with hidden elements, it may be necessary to retrieve their dimensions for various purposes. However, conventional methods of obtaining the height of an element can fail if the element is not visible.

Inefficient Approach

The described approach of temporarily unhiding the element, measuring its height, and then re-hiding it is cumbersome and inefficient.

Alternative Solution

jQuery provides a more efficient solution:

  1. Modify Element Attributes: Temporarily manipulate the element's style attributes:

    • Set position to absolute (optional if the element is already absolute-positioned)
    • Set visibility to hidden (make the element invisible)
    • Set display to block (make the element visible, but not in the main document flow)
  2. Measure Height: Retrieve the height of the element using jQuery's .height() method.
  3. Restore Attributes: Reset the element's style attributes to their original values using the attr() method or by setting the style property directly.

Code Example

<code class="javascript">var previousCss = $("#myDiv").attr("style");

$("#myDiv").css({
    position: 'absolute',
    visibility: 'hidden',
    display: 'block'
});

var optionHeight = $("#myDiv").height();

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

This method allows you to discreetly measure the height of a hidden element without affecting the layout or visibility of the page.

The above is the detailed content of How to Get the Height of a Hidden Element with jQuery?. 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