4

How can I get the height of an element which has got a parent element that has display: none?

An example here: jsfiddle.net

Thanks

Lukas

Joffrey Maheo
  • 2,919
  • 2
  • 20
  • 23
luksak
  • 3,502
  • 2
  • 25
  • 28

6 Answers6

6

Temporarily show()ing an element to retrieve a child's height seems to work OK.

HTML:

<div id="target" style="display:none;">
    <!-- Add a background color to see if it's noticeable -->
    <div style="height:123px; background:#000;"></div>
</div>

JS:

// Show the hidden parent of the element we want the height of
$("#target").show(0, function(){
    // Find and grab the height of the element we want
    the_height = $(this).find("div").height();
// Hide parent and display child's height after it
}).hide().after(the_height);

Demo: jsfiddle.net/Gts6A/72

Marcel
  • 27,922
  • 9
  • 70
  • 85
  • 3
    +1 for a nice trick...but showing and hiding a div will cause a blink effect. – Vivek May 30 '11 at 12:05
  • @Vivek: Doesn't seem to for me. – Marcel May 30 '11 at 12:09
  • This can definitely cause a browser to blink on an older pc. This is because it forces a complete re-layout twice in a row. I'd recommend thoroughly testing this solution before relying on it. – Exelian May 30 '11 at 12:29
  • 1
    `the_height` is an implicit global variable. Implicit globals should be avoided, declare it as a local variable rather. – Šime Vidas May 30 '11 at 12:31
2

You can do this or you can use the hack from this question.

$("#target").parent().show();
var h = $("#target").height();
$("#target").parent().hide();
alert(h);

See fiddle.

Community
  • 1
  • 1
melhosseiny
  • 9,992
  • 6
  • 31
  • 48
1

it's very difficult(in other word you can't) to get the height of hidden element...because dom doesn't consider hidden elements while rendering the page.

Vivek
  • 10,978
  • 14
  • 48
  • 66
1

Hidden elements have an undefined width and height, so it's not possible to get em.

Exelian
  • 5,749
  • 1
  • 30
  • 49
1

This is a bit klunky but you have to have an object rendered before it can be measured.

var $target = $("#target");

$target[0].parentNode.runtimeStyle.display = "block";
var height = $target.height();
$target[0].parentNode.runtimeStyle.display = "none";
alert(height);
Steve Wellens
  • 20,506
  • 2
  • 28
  • 69
0

Either you should display the div or it is impossible to get the height of the hidden elements. I would say, use .show() to show the div, get the height and then use .hide() to hide it again..

Abdul Kader
  • 5,781
  • 4
  • 22
  • 40