how to find real DIV height?
I have the following html structure:
<div id="container"> <h1>This is an h1 element</h1> </div>
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?
Answers
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); console.log(outerHeight); //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> </div>
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(container.style.marginTop.replace("px", "")); var d = parseInt(container.style.marginBottom.replace("px", "")); var e = parseInt(container.style.paddingTop.replace("px", "")); var f = parseInt(container.style.paddingBottom.replace("px", "")); var g = a + c + d + e + f; alert(g);
EDIT
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