Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get height of <div> in px dimension

I have used jQuery library to find out height of a div.

Below is my div element with attributes :

<DIV id="myDiv" style="height:auto; width:78;overflow:hidden"> Simple Test</DIV> 

Below is my jQuery code to get height of <div>

var result = $("#myDiv").css('height'); alert(result); 

After executing above statement I am getting result as "auto". Actually this is I am not expecting, instead of that I want the result in px dimension.

like image 875
pravin Avatar asked Oct 01 '10 12:10

pravin


People also ask

How do I get the height of a div element?

You can use 2 properties, clientHeight and offsetHeight to get the height of the div. clientHeight includes padding of the div. offsetHeight includes padding, scrollBar, and borders of the div.

How do you find the height of an element in pixels?

To get the height and width of an HTML element, you can use the offsetHeight and offsetWidth properties. These properties return the viewable height and width of an element in pixels, including border, padding, and scrollbar, but not the margin.

What is the default height of div?

All block level elements inherit the width of their parent element by default. In your example, the div is inheriting the width of the parent body tag, taking into account any margin or padding on the body element. this doesn't mention height. Which is max(0,content).


2 Answers

Use .height() like this:

var result = $("#myDiv").height(); 

There's also .innerHeight() and .outerHeight() depending on exactly what you want.

You can test it here, play with the padding/margins/content to see how it changes around.

like image 35
Nick Craver Avatar answered Sep 20 '22 11:09

Nick Craver


Although they vary slightly as to how they retrieve a height value, i.e some would calculate the whole element including padding, margin, scrollbar, etc and others would just calculate the element in its raw form.
You can try these ones:

javascript:

var myDiv = document.getElementById("myDiv"); myDiv.clientHeight; myDiv.scrollHeight; myDiv.offsetHeight; 

or in jquery:

$("#myDiv").height(); $("#myDiv").innerHeight(); $("#myDiv").outerHeight(); 
like image 167
Shaoz Avatar answered Sep 18 '22 11:09

Shaoz