Reputation: 539
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
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
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
Reputation: 1013
Use offsetWidth
$("#result").html(
"<br />JQUERY says: " + $("#divA").width() +
"<br />JAVASCRIPT says: " + document.getElementById("divA").offsetWidth;
);
Upvotes: 3