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
I usually get the
height properties directly, like so:
// Get the element with the ID "chicken"
var chicken = document.querySelector("#chicken");
// Get its total width
var width = chicken.getBoundingClientRect().width;
// Get its total height
var height = chicken.getBoundingClientRect().height;
But you could also save the entire
DOMRect object for later use:
// Get the element's size and position
var domRect = chicken.getBoundingClientRect();
// Log its total width
// Log its total height
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.