how to find real DIV height?

I have the following html structure:

<div id="container">
     <h1>This is an h1 element</h1>

When I try to find the height of the container in firefox or chrome div using javascript:

var container = document.getElementById("container");
var offsetHeight = container.offsetHeight;

I get the wrong offsetHeight (also if used with clientHeight). I get only the height of the H1 itself and not the margin-before/margin-after that surround the element.

is there any way to get the real height?


Here's a function that I think will help you:

function outerWidth(elem){
    var curStyle = elem.currentStyle || window.getComputedStyle(elem);
    outerHeight = elem.offsetHeight;
    outerHeight += parseInt(curStyle.marginTop);
    outerHeight += parseInt(curStyle.marginBottom);

    //return outerHeight //If you'd like to return the outerheight

Just call it like this:

<div onclick="outerWidth(this)" id="container">
    <h1>This is an h1 element</h1>

The outer height will be printed in the console, but you can just return it if need be.

Here's a DEMO

I highly recommande JQuery to do these kinda things but for normal javascript, first you have to get the div height, which you already done, then get the margin and padding separately. Just like this

        var container = document.getElementById("container");
        var offsetHeight = container.offsetHeight;

        var a = parseInt(offsetHeight);
        var c = parseInt("px", ""));
        var d = parseInt("px", ""));
        var e = parseInt("px", ""));
        var f = parseInt("px", ""));

        var g = a +  c + d + e + f;


Sorry if you do "document.getElementById('container').style.marginTop" it will return the value with "px", so you have to replace the value to remove the "px", then parse int.

Code above modified

Need Your Help

How to get index of UIButton that viewwithtag in uitableview ios

ios objective-c uitableview

I have a problem: I want to get index of UIButton in tableview. I created uitableview has 2 uibutton in each row, but when i click on uibutton, it get index incorrect.

Zend_db update better error reporting

php zend-framework zend-db

When I update a record, I'm using the result from 'update' to determine if it worked correctly.

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.