Get an element's total width and height in vanilla JS
In jQuery, you can use the
outerHeight() methods to get an element’s total width and height including its padding and borders. You can easily do the same thing in vanilla JS with support back to IE9.
You can use the
Element.getBoundingClientRect() method to achieve this. As explained in the MDN Web Docs:
Element.getBoundingClientRect()method returns the size of an element and its position relative to the viewport.
The element’s size is equal to its
border-widthin the case that the standard box model is being used, or
box-sizing: border-boxhas been set on it.
It returns a
DOMRect object. This object has several properties, but the two we’re interested in are
How to use it
Get the properties directly
I usually get the
height properties directly, like so:
But you could also save the entire
DOMRect object for later use:
A note on margins
If you pass
true to jQuery’s
outerHeight() methods, they’ll also include the element’s margins. I think that’s stupid, personally, since the
margin property in CSS describes the space around an element—and is therefore not part of the element itself.
You can use the native
Element.getBoundingClientRect() method instead of jQuery’s
outerHeight() methods. It returns a
DOMRect object whose
height properties are supported back to IE9.
If you have questions, feedback, or any other suggestions, please do email me. I'd love to hear from you!