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 :-)
<style>
#divA
{
width: 500px;
}
</style>
<body>
<div id="divA">I'm a div. Get my width!</div>
<!-- Just for output -->
<p id=result></p>
<script>
$(document).ready(function()
{
$("#result").html(
"<br />JQUERY says: " + $("#divA").width() +
"<br />JAVASCRIPT says: " + document.getElementById("divA").style.width
);
});
</script>
Use offsetWidth
$("#result").html(
"<br />JQUERY says: " + $("#divA").width() +
"<br />JAVASCRIPT says: " + document.getElementById("divA").offsetWidth;
);
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>
You should use the .offsetWidth
and .offsetHeight
properties. Note they belong to the element, not .style
.
"<br />JAVASCRIPT says: " + document.getElementById("divA").offsetWidth;
请改用document.getElementById(“ divA”)。offsetWidth。
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.