Get an element's total width and height in vanilla JS

In jQuery, you can use the outerWidth() and 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.

Element.getBoundingClientRect()

You can use the Element.getBoundingClientRect() method to achieve this. As explained in the MDN Web Docs:

The Element.getBoundingClientRect() method returns the size of an element and its position relative to the viewport.

The element’s size is equal to its width/height + padding + border-width in the case that the standard box model is being used, or width/height only if box-sizing: border-box has been set on it.

It returns a DOMRect object. This object has several properties, but the two we’re interested in are width and height.

How to use it

Get the properties directly

I usually get the width and 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;

Save the DOMRect object

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
console.log(domRect.width);

// Log its total height
console.log(domRect.height);

A note on margins

If you pass true to jQuery’s outerWidth() and 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.

Summary

You can use the native Element.getBoundingClientRect() method instead of jQuery’s outerWidth() and outerHeight() methods. It returns a DOMRect object whose width and 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!