Jquery get the rendered height of an element?
The rendered height of an element in jQuery can be retrieved using .height()
(height minus padding and border), .outerHeight()
(including padding and border), or .outerHeight(true)
(including margin as well). To measure the height of a hidden element accurately, make sure it is visible first.
Quick rundown of height properties
When dealing with dynamic content, the height of an element can fluctuate based on the content. Here are some key properties and methods to help you measure these changes:
.innerHeight()
: Gets height considering padding but not border or margin, ideal if you love padding but hate margins.getBoundingClientRect()
: Provides a pixel-perfect floating point value of rendered height and even adjusts for CSS transforms (how polite!).document.getElementById('element').clientHeight
: Without jQuery, this retrieves the height minus scrollbar and borders, because who likes scrollbars and borders anyway.document.getElementById('element').offsetHeight
: An alternative without jQuery, this includes scrollbar, borders and possibly padding because some like it extra.
Grabbing measurements like a pro
Here are some techniques and tips to measure height more perfectly every time:
It's not invisible if you can measure it
For elements hidden by CSS (like display: none
), they need to be temporarily visible for the height to be measurable:
Roll with the changes
If content changes due to interactive events or asynchronous operations, recalculate heights after these events:
CSS transforms won't fool you anymore
Use getBoundingClientRect()
because it can handle elements affected by CSS transforms, like rotation and scaling:
Frameworks are your friends
In Vue.js project, reference the element using this.$refs
to get its rendered height:
Into the beyond: alternatives to jQuery
While jQuery offers a straightforward way to measure elements, knowing how to do it in vanilla JavaScript or other frameworks adds more tools in your toolbelt:
- Try finding JavaScript alternatives at [http://youmightnotneedjquery.com/].
- For Vue.js, use
$refs
andgetBoundingClientRect()
to claim your rendered heights. - Also adding
clientHeight
andoffsetHeight
to your plain JavaScript scenario can offer spicy alternatives.
Was this article helpful?