Get Width And Height Of HTML Element Using JavaScript
JavaScript
19/07/2021
There are a few ways you can retrieve the width and height of an HTML element on your page. However, it's important to know what these measurements are made up of: the content, padding, border and margin.
In all the following methods, the margin is always excluded from and the content is always included in the height and width calculations.
Method 1
The offsetHeight and offsetWidth read-only properties return a value that includes the border, padding and scroll bar. If the element is hidden, then both properties will return 0.
const htmlElement = document.getElementById('some-id')
htmlElement.offsetHeighthtmlElement.offsetWidth
Method 2
Similarly, clientHeight and clientWidth are read-only properties. However, the returned value solely includes the padding. Take notice that for inline elements, these properties return 0.
htmlElement.clientHeighthtmlElement.clientWidth
Method 3
Another way to measure an element's dimensions is using getBoundingClientRect(). It's main advantage over the other 2 methods is that it gives you fractional values instead of rounding them to the nearest integer.
const elementDimensions = htmlElement.getBoundingClientRect()elementDimensions.heightelementDimensions.widthIt returns an object of type DOMRect that contains the height and width of the element. And like offset..., the border, padding and scroll bar are included in the measurements.
