Possible Duplicate:
Get element width in px
How can I find the width of divA? This code brings up an empty alert popup.
<script type="text/javascript">
function DisplayResult(){
width = document.getElementById("divA").style.width;
alert(width);
}
var widthFinder = {
find: DisplayResult
};
widthFinder.find();
</script>
<div id="divA">Alert this string's length in pixels</div>
EDIT:
This now alerts “null”. Still not quite what im hoping for.
<html>
<head>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<script type="text/javascript">
function DisplayResult(){
var width = $("#divA").width();
alert(width);
}
var widthFinder = {
find: DisplayResult
};
widthFinder.find();
</script>
<div id="divA" style="display:inline; width:100%;">Alert this string's length in pixels</div>
</body>
</html>
Your code is set to be executed before the DOM is ready, hence why it doesn’t find any element and returns a
nullvalue.I’ve wrapped your function call inside the
$(document).ready()event which prevent the code from being executed before the DOM is ready. I’ve also added()to theDisplayResult()to ensure that it’s being interpreted as a function call.Try out this JSFiddle example.