Javascript Getting Div Height Problem in IE
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:
| Hi! |
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;
}
</style>
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);
}
</script>
HTML Code for Div Containing Table Element
<div id="myDiv">
<table id="myTable">
<tr>
<td>
column1
</td>
<td>
column2
</td>
</tr>
</table>
</div>
<br />
<br />
<input id="myBtn"
type="button"
value="Get Height"
onclick="getDivHeight();" />
Output:
