Checking the Dimensions of an HTML Element in Vanilla JavaScript
November 29, 2020
Because of the way that web technologies work, the sizes of things in your web page might not be predictable. This is especially true with modern standards of responsiveness and the multitude of screen shapes necessitating those standards. You might leave you wondering how to get the size of an HTML element using vanilla JavaScript. There are a few different ways to measure this.
Full Height and Width
To get the full size of the space an element takes up, we can use HTMLElement.offsetHeight
and HTMLElement.offsetWidth
. These properties of an element provide values that include the width of scrollbars, padding, and border.
// Grab an element with id target
var element = document.getElementById('target');
// Check its height and width
console.log('h', element.offsetHeight);
console.log('w', element.offsetWidth);
Another way to achieve these same measurements is using getBoundingClientRect()
but that function would not provide accurate readings if transforms were applied to the element in question. It's better to get in the habit of using offsetHeight
and offsetWidth
for this because those properties account for transforms applied to our element.
Looking at the Content
Instead of getting the full size of an element, we might be interested in looking at the size of its content. Here's a method that ignores borders, margins, and scrollbars: Element.clientHeight
and Element.clientWidth
. These properties provide the dimensions of an element's content including padding.
// Log the height of visible content & padding
console.log('h', element.clientHeight);
// Log the width of visible content & padding
console.log('w', element.clientWidth);
We can also look at the size of the content regardless of how much is currently visible onscreen. Element.scrollHeight
and Element.scrollWidth
provide the height and width of the content--all of the content, even if scroll bars are in use and not all the content is currently in view.
// Log full height of content
console.log('h', element.scrollHeight);
// Log full width of content
console.log('w', element.scrollWidth);
Build Something
These are just some tiny techniques that you might need down the line. Keep them on your toolbelt and use them to build something! For example, you could store an element's height and width in data attributes when the document loads, and write CSS rules that attenuate to those data attributes to change the style of elements based on size. Another example where this stuff might be useful is finding the center of an element; we can get the element's height and width and divide those in half. You'll find little ways to use these techniques the more you practice and learn.