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

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

How do you find the current width of a

in a cross-browser compatible way without using a library like jQuery?


Solution 1:


Solution 2:

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

Solution 3:

All Answers are right, but i still want to give some other alternatives that may work.

If you are looking for the assigned width (ignoring padding, margin and so on) you could use.

getComputedStyle(element).width; //returns value in px like "727.7px"

getComputedStyle allows you to access all styles of that elements. For example: padding, paddingLeft, margin, border-top-left-radius and so on.

Solution 4:

You can also search the DOM using ClassName. For example:


This will return an array. If there is one particular property you are interested in. For example:

var divWidth = document.getElementsByClassName("myDiv")[0].clientWidth;

divWidth will now be equal to the the width of the first element in your div array.

Related:  Difference between Date(dateString) and new Date(dateString)

Solution 5:

Actually, you don’t have to use document.getElementById("mydiv") .
You can simply use the id of the div, like:

var w = mydiv.clientWidth;
var w = mydiv.offsetWidth;

Solution 6:

call below method on div or body tag onclick=”show(event);”
function show(event) {

        var x = event.clientX;
        var y = event.clientY;

        var ele = document.getElementById("tt");
        var width = ele.offsetWidth;
        var height = ele.offsetHeight;
        var half=(width/2);
          //  alert('right click');
           //   alert('left click');