How To Get Element Width With JavaScript

In this article, you will look at how to get an element's width using javascript.

There are several properties in javascript to get an element's width. I will discuss some of them.

[1] Using the offsetWidth property.

We can use the offsetWidth property to display a specific element's width. The offsetWidth property returns the width of an element including its padding, border etc..

The below example returns 172.
Demo : using offsetWidth property
<span>This is a span element.</span>
<script>
  let textWidth = document.getElementById("out");
  document.write(textWidth.offsetWidth)
</script>
Try it Yourself »

Now include the border property with its value 5px solid red to add border of the span element.

The above example have returned 172. Now, we have added 5px of border to the span element. So, it will return 182 which is equal to the original width plus the horizontal border.

Demo : Get width including border
<span style="border:5px solid red" id="out">
  This is a span element.
</span>
<script>
  let textWidth = document.getElementById("out");
  document.write(textWidth.offsetWidth)
</script>
Try it Yourself »

[2] Using the getBoundingClientRect() method.

The getBoundingClientRect() method returns a DOMRect object which has a width property.

For example, the below code returns 176.35 which is equal to the current width plus the horizontal border.

Demo : Get width using getBoundingClientRect() method
<span style="border:2px solid red;" id="out">
  This is a span element.
</span>
<script>
  let textWidth = document.getElementById("out").getBoundingClientRect()
  document.write(textWidth.width)
</script>
Try it Yourself »