Click to See Complete Forum and Search --> : How to detect the width of an element?


delerious
12-04-2003, 03:19 PM
How do I determine the width of an element (such as DIV or A) on a page using Javascript?

batfink
12-04-2003, 04:52 PM
Assume you have a div with an id of mydiv:

var x = document.getElementByID("mydiv").style.width;

fredmv
12-04-2003, 05:34 PM
Originally posted by batfink
document.getElementByID("mydiv").style.width;
One slight typo — it's getElementById.

batfink
12-05-2003, 10:08 AM
oops:eek: and I have not even got fat fingers to excuse me.

delerious
12-05-2003, 11:26 AM
That doesn't work in IE, Opera, or Mozilla.

neil9999
12-05-2003, 11:43 AM
It does in IE: try this:

<html>

<head>
</head>

<body onload="alert(document.getElementById('mydiv').style.width);">
<div id="mydiv" style="width:200">
Hello
</div>
</body>

</html>

fredmv
12-05-2003, 11:53 AM
It doesn't work most likely because you aren't referencing the correct property. It won't return a value for width if it isn't defined. The only way you can access it is using something like getComputedStyle (http://www.csie.ntu.edu.tw/~b7506051/docs/GeckoDOM/examples7.html).

lukezweb
12-05-2003, 11:58 AM
var td = document.getElementsByTagName('TD');
for(a=0; a<td.length; a++){
var widthofdiv = td[a].width;
}}

batfink
12-05-2003, 04:28 PM
I have tried the code in IE, NN and Opera and they all work!

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">

<html>
<head>
<title>Untitled</title>
</head>
<body>
<input type="button" value="Find width of DIV" onClick="alert(document.getElementById('mydiv').style.width)">
<div id="mydiv" style="width:300px; height:100px"></div>
</body>
</html>

As fredmv points out I think we need to see your code.

delerious
12-05-2003, 07:52 PM
OK thanks for the replies, everyone. The reason why the document.getElementByID("mydiv").style.width code didn't work is because I am not fixing the width of my DIV. But the getComputedStyle() works, and using offsetWidth also works.