With a div element in a parent div that is hidden with display:none.

  • I'm dumping the jQuery textarea element to the console. I see that the scrollHeight property of the 0th element is 88.
  • I try to read this property to a var (using $(element)[0].scrollHeight or $(element).prop('scrollHeight') and I'm getting 0.

I also tried to set the textarea to position: absolute and display: block with jQuery, before the read, with the same result.

How can I read the property correctly?

What is the size of an element when display:none? 0px by 0px

The element hasn't been rendered or painted anywhere on the screen, and so it truly occupies zero pixels worth of space. The question of if it was visible, how much space it would consume is tricky to answer, because answering it accurately means turning the hypothetical into a reality. We would need to actually render it to get a reliable measure of its size.

Generally speaking, this involves either:

  1. Toggling - Quickly making the element visible, checking the height, and restore back

    When toggling, you might be able to make visible and undo in between paint cycles, but there's no guarantee. Especially if the element you're looking to measure is deeply nested inside a hidden parent.

  2. Cloning - Emulate the element's properties as best you can & rendering off screen

    When cloning, an element's dimensions are based on a large number of other elements and properties surrounding it. Depending on the complexity of your page, there's also no guarantee that creating an element offscreen will yield the same exact dimensions that the original would.

There are several solutions laid out in the following questions, but most follow that basic pattern:

There's also a library called jQuery.Actual (2.4KB) which abstracts away some of that work:

Here's their own Demo Page and also a Stack Snippet:

<!-- begin snippet: js hide: true console: true babel: false --> <!-- language: lang-js -->
console.log("width: ", $("#inner").actual("width"))
console.log("height: ", $("#inner").actual("height"))
<!-- language: lang-css -->
#outer, #inner {
  margin: 10px;
  padding: 10px;
}
#outer {
  background: #d1e3ef;
}
#inner {
  background: #9ebae9;
}
<!-- language: lang-html -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.2.4/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery.actual/1.0.19/jquery.actual.min.js"></script>

<div id="outer" style="display:none">
  <code>#outer</code>
  <div id="inner">
    <code>#inner</code>
  </div>
</div>
<!-- end snippet -->

Example