1

I know it will be totally embarassing, but I'm a blockhead today!

Why doesn't Javascript return the width here?

The output of the below code is:

JQUERY says: 500;

JAVASCRIPT says: (that's the problem. Javascript returns just NOTHING)

Here' the fiddle-link: https://jsfiddle.net/w62zg76f/1/

UPDATE: Thank you guys! Solution is .offsetWidth of course

(I knew it would be embarassing :-)

$(document).ready(function(){

  $("#result").html(
  "<br />JQUERY says: " + $("#divA").width() + 
  "<br />JAVASCRIPT says: " + document.getElementById("divA").style.width
  );

});
#divA{
  width: 500px;
}
<div id="divA">I'm a div. Get my width!</div>

<!-- Just for output -->
<p id=result></p>
AliNajafZadeh
  • 1,216
  • 2
  • 13
  • 22
  • 3
    As there is no inline styles `width` applied to element, `.style.width` will be undefined. [How to find the width of a div using raw Javascript?](http://stackoverflow.com/questions/4787527/how-to-find-the-width-of-a-div-using-raw-javascript) and [How do I retrieve an HTML element's actual width and height?](//stackoverflow.com/q/294250) – Tushar Jan 24 '17 at 14:18
  • 1
    Probably a good time to mention that if you separated out your lines of code, built your HTML, and then tried to apply it, you'd probably be able to see the actual error. – tymeJV Jan 24 '17 at 14:20
  • 1
    oh gosh. Yes! And how to get the width WITHOUT inline styles applied. I already tried without .style – Manny_user3297459 Jan 24 '17 at 14:20
  • 1
    http://stackoverflow.com/questions/21064101/understanding-offsetwidth-clientwidth-scrollwidth-and-height-respectively – kukkuz Jan 24 '17 at 14:22
  • 1
    if you actually googled it (like most of us who gave answers probably did) you'd have found the SO answer for this issue – zerohero Jan 25 '17 at 06:28

4 Answers4

3

Use offsetWidth

$("#result").html(
"<br />JQUERY says: " + $("#divA").width() + 
"<br />JAVASCRIPT says: " + document.getElementById("divA").offsetWidth;
);

HTMLElement.offsetWidth

Tim Barnett
  • 1,012
  • 5
  • 9
3

document.getElementById("divA").style.width return you undefined, you have to use the offsetWidth

$(document).ready(function(){

  $("#result").html(
  "<br />JQUERY says: " + $("#divA").width() + 
  "<br />JAVASCRIPT says: " + document.getElementById("divA").offsetWidth
  );

});
#divA{
  width: 500px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="divA">I'm a div. Get my width!</div>




<!-- Just for output -->
<p id=result></p>
Teshtek
  • 1,212
  • 1
  • 12
  • 20
2

You should use the .offsetWidth and .offsetHeight properties. Note they belong to the element, not .style.

"<br />JAVASCRIPT says: " + document.getElementById("divA").offsetWidth;
zerohero
  • 593
  • 4
  • 15
2

use document.getElementById("divA").offsetWidth instead.