Manny_user3297459
Manny_user3297459

Reputation: 539

Javascript returns no width

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>

Upvotes: 1

Views: 195

Answers (4)

Teshtek
Teshtek

Reputation: 1342

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>

Upvotes: 3

user6146785
user6146785

Reputation:

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

Upvotes: 2

zerohero
zerohero

Reputation: 583

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

"<br />JAVASCRIPT says: " + document.getElementById("divA").offsetWidth;

Upvotes: 2

Tim Barnett
Tim Barnett

Reputation: 1013

Use offsetWidth

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

HTMLElement.offsetWidth

Upvotes: 3

Related Questions