Get width and height of element in Javascript with this one simple function

No more needing to remember whether you want to use width or innerWidth to get the correct value

Published March 15th 2020

For years, I used to use write out functions running several lines of code to get the height and the width of elements. That was until today, when I came across a Javascript method I hadn't heard of before: getBoundingClientRect();

This single method returns an object containing the height, width, and – if you don't need to support IE8 or earlier (which, let's be honest, at this point in 2020, you really shouldn't be anyway) – the position of the element on the page.

Combining this, with a simple function like so:

function getSizeById(e) {
    var element = document.getElementById(e);
    return element.getBoundingClientRect();
}

Means you can quickly get the width or height of an element – let's say in this case, a full width hero with the ID of banner – like so:

// Width
getSizeById('banner').width

// Height
getSizeById('banner').height

This sort of function is incredibly useful for working out the size of elements when you want to use a service like Imgix or a package like Glide to return appropriately sized images.