This post will discuss how to get the width and height of an element with pure JavaScript.

There are several properties in JavaScript to get the width and height of an element. This post provides an overview of some of these properties.

1. Using clientWidth and clientHeight properties

In JavaScript, you can use the clientWidth and clientHeight properties to return the height of an element, including the padding but excluding the border, margins, or scrollbars. Basically, they return the actual space used by the displayed content.

For example, the following code returns ‘520 × 120.’

JS


HTML


CSS



Edit in JSFiddle

 
The scrollWidth and scrollHeight properties are similar to the clientWidth and clientHeight properties, except they return the actual size of the content, regardless of how much is actually visible.

2. Using offsetWidth and offsetHeight properties

Alternatively, if you need to include border and scrollbars, you can use the offsetWidth and offsetHeight properties. They return the dimensions of the visible content of the element, including padding, borders, and scrollbars. In other words, they return the total amount of space an element occupies.

For example, the following code will return ‘522 × 122’.

JS


HTML


CSS



Edit in JSFiddle

3. Using getBoundingClientRect() method

The getBoundingClientRect() method returns the size of an element. It returns a DOMRect object with width, height, left, top, right, bottom, x, and y properties. The returned width and height of the element can be fractional (unlike the above properties) and include padding and borders.

For example, the following code returns ‘522 × 122’.

JS


HTML


CSS


Edit in JSFiddle

4. Using width and height properties

You can also use width and height properties to get the actual width and height of an element with units intact. Note that this will only work when the element has width and height attribute set using the style attribute.

JS


HTML



Edit in JSFiddle

That’s all about getting the width and height of an element with JavaScript.