Get the width and height of a div in javascript

I am trying to get the width and height of a div when the user changes it and passes that number to another page. I can't figure out how to get width and height.

<script> $(function() { $( "#set div" ).draggable({ stack: "#set div", preventCollision: true, containment: $('#main_content'), stop: function(event, ui) { var mydiv = document.getElementById("set"); var pos_x = ui.offset.left; var pos_y = ui.offset.top; var width = mydiv.style.width; ----THIS DOESN'T WORK var height = mydiv.style.height; ----THIS DOESN'T WORK var window_width = window.innerWidth; var window_height = window.innerHeight; var need = ui.helper.data("need"); console.log(pos_x); console.log(pos_y); console.log(width); console.log(window_width); console.log(need); //Do the ajax call to the server $.ajax({ type: "POST", url: "updatecoords.php", data: { x: pos_x, y: pos_y, need_id: need, width: width, height: height, window_width: window_width, window_height: window_height} }).done(function( msg ) { alert( "Data Saved: " + msg ); }); } }); }); </script> 

What is the right way to do this?

+7
source share
4 answers

Since you are already using jQuery, you can simply do:

 var width; if (need == 1) { width = $("#web").width(); } else { width = $("#set").width(); } 
+6
source

It is wrong to use ele.style.width to get the width of an element !!!!!!

In native JavaScript, you can get a CSS element in two ways:

Standard method

 window.getComputedStyle(ele) 

For example,

 var ele = document.getElementById("content"), // Do not use # eleStyle = window.getComputedStyle(ele); /* Below is the width of ele */ var eleWidth = eleStyle.width; 

IE (IE 8 and earlier)

 element.currentStyle 

For example,

 var ele = document.getElementById("content"), // Do not use # eleStyle = ele.currentStyle; /* Below is the width of ele */ var eleWidth = eleStyle.width; 

Why not use ele.style ?

ele.style is simply an attribute attribute of ele . If you use ele.style.width , you just get the width of ele.style , not the actual width of ele .

If you did something like:

 ele.style.width = "55px" 

When using ele.style.width you get "55px". If you do not, you will get undefined.

How to do in jQuery?

Use $ele.width() (if you want an β€œexact” width, use $ele.outWidth() ), jQuery did everything for you.

+18
source

In plain vanilla javascript use

 var width = mydiv.offsetWidth; var height = mydiv.offsetHeight; 

This will give you numerical values ​​or

 var width = mydiv.offsetWidth + 'px'; var height = mydiv.offsetHeight + 'px'; 

If you want them in CSS format.

+10
source

Since you are using jQuery, you probably want to know about the following:

$ ('# identifier'). OuterWidth () $ ('# Identifier'). OuterWidth (true)

It is very comfortable. This allows you to find the full width of the div field (indent, border, width, and (optional argument)).

http://api.jquery.com/outerWidth/

+1
source

All Articles