Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery height() returns 0 on a visible div - why?

Tags:

jquery

css

I have a container (thetext1) with a set height of 360px. "thetext1" contains two divs - one on the left and one floated to the right - into both of which content is delivered through an ajax call.

There will be times when the content in one or other of these divs exceeds 360px and so I want to increase the height of thetext1 accordingly.

My test code

newhgt = $('#thetext1').find('div.rhs').css("background", "pink").height(); 

returns 0 - (my selector is correct as the targeted div is perfectly pink!).

Why is this? I know - from answers to previous posts on this site - that the solution is to add overflow: hidden thetext1, but I would like to understand why my attempt to get the height of the rhs and lhs div is failing.

like image 372
TomBaine Avatar asked Feb 15 '12 11:02

TomBaine


People also ask

Why does my div have zero height?

The reason why the height or the containers is 0 is because you are floating all the content inside them and floated elements don't expand the height (or width) of their parents.


2 Answers

Make sure the code is inside the $(window).load [not $(document).ready ]

$(window).load(function () {     newhgt = $('#thetext1').find('div.rhs').css("background", "pink").height(); }); 
like image 89
Gazzer Avatar answered Sep 25 '22 17:09

Gazzer


I had the same problem, and I noticed one thing, the div needs to be visible when you call .height();

But, even if the div is visible, the parents of this div needs to be visible. So you must garantee that parents div are visible (display != none)

writing a $('#div').parent().show(); will make a parent visible, you may need anothers parent().show();

like image 28
Daniel Avatar answered Sep 24 '22 17:09

Daniel