6

I think it should return 0 for display:none elements. but it doesn't, at least for 1.10.1

<div id="a" style="display:none">
    asdf
    asdfasdf<br>
    sadf
</div>

alert($('#a').outerHeight(true))

http://jsfiddle.net/pUuAz/

user2665846
  • 63
  • 1
  • 3

2 Answers2

9

jQuery gives you the height of the element regardless to if it's displayed on the screen.

If you want it to ignore an hidden element use the following:

$('#a').is(':visible') ? $('#a').outerHeight(true) : 0;
Adam Tal
  • 5,911
  • 4
  • 29
  • 49
  • This is just half-true. jQuery will give the height just if the element is directly hidden, but will return ```0``` in case the element set to ```display:none``` is an ancestor of the targeted element (see https://codepen.io/anon/pen/bKQvVN?editors=1111) – Kamafeather Jun 28 '18 at 13:52
2

digging into $.css to $.style to $.cssHooks to $.cssHooks.height.get we see the culprit:

function ( elem, computed, extra ) {
            if ( computed ) {
                // certain elements can have dimension info if we invisibly show them
                // however, it must have a current display style that would benefit from this
                return elem.offsetWidth === 0 && rdisplayswap.test( jQuery.css( elem, "display" ) ) ?
                    jQuery.swap( elem, cssShow, function() {
                        return getWidthOrHeight( elem, name, extra );
                    }) :
                    getWidthOrHeight( elem, name, extra );
            }
}

it seems they swap the style, rip the value, then swap it back to display:none.

dandavis
  • 16,370
  • 5
  • 40
  • 36