We can use JavaScript to get the width of an element by using the offsetWidth property.

document.getElementById("div2").offsetWidth;

You can also get the width of an element using the width property, but one problem we see a lot is if no width is set for the element, nothing will be returned for the width. This is why we prefer to always use the offsetWidth property to get the width of an element. Also, note that the offsetWidth property will return the width of the element plus any padding and/or border-width that might be added to the element.


Let’s say we have the following HTML:

This paragraph is in a div that we want to get the width of.


If we want to get the width of #div1 with padding, we would use the offsetWidth property;

document.getElementById("div1").offsetWidth;

Getting the width of an element can also be done using jQuery with the width() and outerWidth() methods.

Using JavaScript to Get and Change the Width of an Element

In the example below, we will create a div and the ability to add text to the div. Each time we add new text to the div, it will increase the width of the div. We will then let the user check the width of the div whenever they want. Here is the initial HTML setup:

This is some text.
Add text
Get Width

We can utilize both an onclick event and the innerHTML property to add new text to #div2.

Then we can use the offsetWidth property to get the width value of #div2. Finally, we will use the textContent property to display the new width results.

Here is the code:

function addText(){
  var currHTML = document.getElementById("div2").innerHTML;
  currHTML += " This is some more text.";
  document.getElementById("div2").innerHTML = currHTML;
};
function getWidth(){
  var width1 = document.getElementById("div2").offsetWidth;
  document.getElementById("results").textContent = width1;
};

The final code and output for this example is below:

Code Output:

This is some text.
Add text
Get Width

Full Code:

This is some text.
Add text
Get Width


<script>

function addText(){
  var currHTML = document.getElementById("div2").innerHTML;
  currHTML += " This is some more text.";
  document.getElementById("div2").innerHTML = currHTML;
};
function getWidth(){
  var width1 = document.getElementById("div2").offsetWidth;
  document.getElementById("results").textContent = width1;
};

</script>

Hopefully this article has helped you understand how to use JavaScript to get the width of an element.

Categorized in:

JavaScript,

Last Update: March 14, 2024