Javascript Getting Div Height Problem in IE

Updated on 23 Mar 2012,
Published on 22 Sep 2008

Getting Div Height using Javascript in IE is very common problem. A bad thing is Internet Explorer refuses to return the value of offsetHeight or clientHeight of targeted Div for some reasons. Generally IE6 or later versions return the value of offsetHeight but could not evaluate the clientHeight of the Div element using javascript dynamically. FireFox works like a charm that returns the approximate offsetHeight as well as clientHeight of the Div element very easily. If Div contains some nested HTML elements such as HTML table then violating the W3C rules may result as a problem of unexpected output of DOM functionality using Javascript in Internet Explorer. "Laurent Coene" one of our ezine readers asked about this problem of getting Div height using Javascript, he asked:


Any idea why offsetHeight and clientHeight do not take tables into account when in a div? Example:

... document.getElementById("myDiv").clientHeight returns 0!! (same for offsetHeight)


Above javascript function will work fine in FireFox whereas IE needs some other hints to evaluate the height of the Div. You can pass out this problem using CSS style as follows:

<style type="text/css">
    #myDiv {
        width: 200px;
        overflow: auto;

Above CSS rule contains width and overflow style properties that will direct the IE to calculate the height of the Div dynamically using javascript. Combination of width and overflow generates the logical boundary for HTML Div element that enables the IE or other browsers to return the estimate value of offsetHeight or clientHeight.

You can use the following code to test the Javascript offsetHeight and clientHeight properties:

Javascript Code for getting Div Height

<script type="text/javascript">
    function getDivHeight() {

        alert("offsetHeight: "
                + document.getElementById('myDiv').offsetHeight
                + " \nclientHeight: " 
                + document.getElementById('myDiv').clientHeight);

HTML Code for Div Containing Table Element

<div id="myDiv">
    <table id="myTable">
<br />
<br />
<input id="myBtn" 
        value="Get Height" 
        onclick="getDivHeight();" />


2 Responses to "Javascript Getting Div Height Problem in IE"
Actually, this is wrong. I have a script which attempts to alert me the obj.offsetHeight and for a div which has height defined both in the header styles and inline in the div tag. FF 3.0 returns a value of zero for both (div height is 200), so far the only thing that actually reads the div height is, which FF does not support. But this thing about FF being easy and IE being the problem, guess again.
Overflow:hidden; also worked. This would atleast avoid any risk of bringing in any unwanted scrollbars. Thanks for the tip.
Leave a Comment
* required
* required
* will not be published
* optional
* hint:
  • Subscribe via Email