2

Please look at the following link.

http://jsfiddle.net/YJMrE/

HTML:

<div id="test">
    <div id="test1">test 1</div>
    <div id="test2">test 2</div>
</div>

Javascript:

$(document).ready(function(){
    $("#test").hide();
    alert($("#test").height());
    alert(document.getElementById("test").getBoundingClientRect().height);
});

How is jquery alone able to get the height of the hidden div? Thanks!

mumair
  • 2,768
  • 30
  • 39
Gautham Renganathan
  • 647
  • 1
  • 9
  • 18

5 Answers5

1

Use this for your script:

$(document).ready(function(){
    var x = document.getElementById("test").getBoundingClientRect().height;
    $("#test").hide();
    alert($("#test").height());
    alert(x);
});
Iswanto San
  • 18,263
  • 13
  • 58
  • 79
1

In plain JavaScript you can do something like this and it should work:

// $("#test").hide();
// alert($("#test").height());

var el = document.getElementById("test");
el.style.position = 'absolute';
el.style.visibility = 'hidden';

alert(el.offsetHeight); // 40

jQuery is probably doing the magic for you in some other way. It's not reliable to get dimensions of hidden objects with display: none.

Edit: Here's the jQuery code that handles dimensions. You'll have to connect some dots but it doesn't seem very complicated.

elclanrs
  • 92,861
  • 21
  • 134
  • 171
1

You can get height of div using,

$('#test1').height();
$('#test2').height();

height() function computes height of given element.

Kautil
  • 1,321
  • 9
  • 13
1

I didn't get much from the other answers and wanted to know the same thing and found the relevant lines in the jQuery 3.0.0-pre source.

These properties get temporarily added to the element using this swap function if getClientRects() or getBoundingClientRect() don't return anything useful:

{ position: "absolute", visibility: "hidden", display: "block" }

Then it calls val = elem.getBoundingClientRect()[ name ]; to get the width (line 127 - 3.0.0-pre).

btbright
  • 96
  • 1
  • 2
0

Notice the difference : http://jsfiddle.net/YJMrE/5/

Jquery hides it, so it knows what the hidden element's height was before hiding.

While javascript simply returns the current height.

$(document).ready(function(){        
    alert(document.getElementById("test").getBoundingClientRect().height); // 40
    $("#test").hide();    
    alert(document.getElementById("test").getBoundingClientRect().height); // 0
});
loxxy
  • 12,990
  • 2
  • 25
  • 56