Reputation: 345
I've been trying for a while now to 'get' the height and width of a div on my webpage. I've tried many things, some are:
document.getElementById("header").getHeight();
.height();
.height;
.pixelHeight()
and all other 'obvious' possibilites. Any help please? Its just a simple div with a width and a height:
<style>
#header {
width: 500px;
height:100px;
background-color:black;
border: 2px solid red;
}
</style>
<body>
<div id="header" style="position:absolute" onclick="testjs()" />
<script language="javascript" type="text/javascript">
var hdiv = document.getElementById("header");
function testjs()
{
hdiv.style.height="221px";
}
/////////////////////////////////////
hdiv.getHeight(); ???????
//////////////////////////////////////
</script>
I want to 'get' the div's height and width because eventually the user will be able to alter the height and width dynamically.
Upvotes: 1
Views: 4582
Reputation: 1563
if you don't use jQuery try this:
document.getElementById('someDiv').clientHeight;
document.getElementById('someDiv').offsetHeight;
document.getElementById('someDiv').scrollHeight;
Depend what you need.
Upvotes: 0
Reputation: 2928
example -
var divheight = document.getElementById('divId').offsetHeight;
refer this -
http://www.w3schools.com/jsref/dom_obj_all.asp
Upvotes: 0
Reputation: 2538
to get height use
document.getElementById("header").offsetHeight
and for width use
document.getElementById("header").offsetWidth;
Upvotes: 10
Reputation: 3496
You should think about getting jQuery, as then you can just this and more very easily:
$("#header").width(); // Gets the width;
$("#header").width(50); // Set width to 50;
$("#header").height(); // Gets the height;
$("#header").height(50); // Set height to 50;
It'll make your life a lot easier in the long run too. Writing with native Javascript can be cumbersome as it requires more code and lots of cross browser testing.
Upvotes: 3