By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
459,287 Members | 1,665 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 459,287 IT Pros & Developers. It's quick & easy.

Finding element dimension values width and height

100+
P: 143
Hi

Is it actually possible to find the current size (in pixels) of a html element, regardless of whether or not these attributes have been set, or even if a percentage value was used?

My case: I want to find the height / width of a span tag or the height / width of a div tag. I've browsed the DOM but I can't figure out what to use. I've even tried directly accessing properties .height .width (which works for images) or .style.height .style.width.

If it's possible, that's great - it's pretty much all I need to know. =)

Thanks
Dec 5 '06 #1
Share this Question
Share on Google+
5 Replies


ronverdonk
Expert 2.5K+
P: 4,258
A sample for your DIV width question:
[html]<html><head></head><body>
<div id='test' style='width:300px;'>
</div>
<script type="text/javascript">
var w = document.getElementById("test").style.width;
alert('width='+w);
</script>
</body></html>[/html]
For an excellent tutorial on DOM usage, see link DOM Reference

Ronald :cool:
Dec 5 '06 #2

100+
P: 143
Thanks Ronald, but as I mentioned in my previous post - the dimension won't be specified, or at best, will be specified in percentage. I see that in your example, you specifically specified the width.

Is it possible to determine the dimensions without specifically setting the dimension in pixels?
Dec 5 '06 #3

100+
P: 143
Just posting the answer in case anyone else finds it useful.

Look at the clientWidth and clientHeight properties.

This is what I was looking for in my particular case. Something that would return the dimensions in pixels, even if they hadn't been set in a stylesheet, or if they were set using percentage values.

example:

Expand|Select|Wrap|Line Numbers
  1. <div id="testing">lorem ipsum</div>
  2. <script type="text/javascript">
  3.   var test = document.getElementById("testing");
  4.   alert("width: "+clientWidth+"px");
  5. </script>
  6.  

I believe you could use offsetHeight and offsetWidth too, though these also take into account possible scoll bars etc (I think). I still have more reading to do in Javascript.
Dec 7 '06 #4

P: 1
<div id="testing">lorem ipsum</div>
<script type="text/javascript">
var test = document.getElementById("testing");
var clientWidth = test.offsetWidth;
alert("width: "+clientWidth+"px");
</script>
Mar 13 '08 #5

P: 13
try these functions

not sure if these functions work with scrollbars in view but worth a shot
Mar 27 '08 #6

Post your reply

Sign in to post your reply or Sign up for a free account.