Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to find the width of a div using vanilla JavaScript?

How do you find the current width of a <div> in a cross-browser compatible way without using a library like jQuery?

like image 235
Joda Maki Avatar asked Jan 24 '11 21:01

Joda Maki


People also ask

Is a div 100% width by default?

auto automatically computes the width such that the total width of the div fits the parent, but setting 100% will force the content alone to 100%, meaning the padding etc. will stick out of the div, making it larger than the parent. so setting the 'width' to 'auto' would be better? Yes, but that's the default anyway.

How do you find the width of an element in pixels?

To get the width of a specific HTML Element in pixels, using JavaScript, get reference to this HTML element, and read the clientWidth property of this HTML Element. clientWidth property returns the width of the HTML Element, in pixels, computed by adding CSS width and CSS padding (top, bottom) of this HTML Element.


2 Answers

document.getElementById("mydiv").offsetWidth 
  • element.offsetWidth (MDC)
like image 100
Andy E Avatar answered Sep 28 '22 16:09

Andy E


You can use clientWidth or offsetWidth Mozilla developer network reference

It would be like:

document.getElementById("yourDiv").clientWidth; // returns number, like 728 

or with borders width :

document.getElementById("yourDiv").offsetWidth; // 728 + borders width 
like image 26
khrizenriquez Avatar answered Sep 28 '22 16:09

khrizenriquez