This post will discuss how to get the width of a div container in JavaScript and jQuery.

1. Using JavaScript

In pure JavaScript, you can use the clientWidth property to get the width of the div container. It returns the actual space used by the displayed content, including its horizontal padding. For example, the following code returns 410 value.

JS


HTML


CSS



Edit in JSFiddle

 
Alternatively, you can use the offsetWidth property if you need the total amount of space the div container occupies. It returns the width of the div container, including the padding, borders, and scrollbars. For example, the following code returns 412 value.

JS


HTML


CSS



Edit in JSFiddle

 
When the container’s width is set by the style attribute, you can use the width property to get width with units intact.

JS


HTML



Edit in JSFiddle

 
Another plausible way is to use the getBoundingClientRect() method, which returns the size of the div container. The returned object contains the width property, whose value includes padding and border. For example, the following code returns 412 value.

JS


HTML


CSS



Edit in JSFiddle

2. Using jQuery

With jQuery, you can use the .width() method to get the div container’s content width. For example, the following code returns 100.

JS


HTML


CSS



Edit in JSFiddle

 
The .width() method returns a unit-less value. If you need width with units intact like 400px, use .css("width") instead.

JS


HTML


CSS



Edit in JSFiddle

 
Alternatively, if you need to include padding and borders (and optionally the margin), consider using the .outerWidth() method. For example, the following code returns 412.

JS


HTML


CSS



Edit in JSFiddle

That’s all about getting the width of a div container in JavaScript and jQuery.