Finding height of auto-sized element?

D

Danny@Kendal

Is there a way to find the size of a <div> element where the height either
hasn't been specified or is set to 'auto'?

document.getElementById('myId').style.height returns either nothing or
'auto'.
 
M

Michael Winter

Is there a way to find the size of a <div> element where the height
either hasn't been specified or is set to 'auto'?

document.getElementById('myId').style.height returns either nothing or
'auto'.

And it shouldn't do anything but that. The style object represents inline
styles: those set by the style attribute or modification of the style
object itself. What you need is the calculated (computed) style.

In DOM-compliant browsers, you can use the getComputedStyle method to
return a computed style object. In IE (and other browsers that decided to
implement it), you can use offsetHeight:

<div id="myDiv">
Some content
</div>
<!-- Add BR elements to easily see changes -->

var getRefById = function() {return null;};
if(document.getElementById) {
getRefById = function(i) {return document.getElementById(i);};
} else if(document.all) {
getRefById = function(i) {return document.all || null;};
}

function test() {
var d = getRefById('myDiv'), h = '0px', o;

if(d) {
if((o = document.defaultView) && o.getComputedStyle) {
h = o.getComputedStyle(d, null).height;
} else if('number' == typeof d.offsetHeight) {
h = d.offsetHeight + 'px';
}
}
// 'h' should now contain the height of 'myDiv', or 0px
}

Note that the value, h, is a string, not a number. This is because CSS
lengths can be specified in various units. However, all my tests returned
values in pixels.

Hope that helps,
Mike
 
M

Mike Foster

Danny@Kendal said:
Is there a way to find the size of a <div> element where the height either
hasn't been specified or is set to 'auto'?

document.getElementById('myId').style.height returns either nothing or
'auto'.


Try...

function getOffsetHeight(id)
{
h = Number.NaN;
if (document.getElementById) {
var ele = document.getElementById(id);
if (ele && typeof ele.offsetHeight != 'undefined') {
h = ele.offsetHeight;
}
}
return h;
}

-
Mike Foster
http://Cross-Browser.com
-
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Staff online

Members online

Forum statistics

Threads
473,755
Messages
2,569,534
Members
45,007
Latest member
obedient dusk

Latest Threads

Top