George Smith
George Smith

Reputation: 505

jQuery get the height of an element with display:none property

Is there an easy way to get the height of a parent div which has a hidden child div inside? If not, what could be the hard way to achieve such a result?

PS: I know that this topic might be repetitive, but the other topics I have found were all with negative scored best answers.

var getHeight = $(".parent").height();

console.log(getHeight);
.parent{
  position:absolute;
  top:0;
  left:0;
}
 
.visibleChild{
  position:relative;
  height:20px;
  background-color:red;
}
 
.hiddenChild{
  display:none;
  height:20px;
  background-color:green;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<div class="parent">
  <div class="visibleChild">
    This div is visible.
  </div>
  <div class="hiddenChild">
    This div is hidden.
  </div>
</div>

Upvotes: 1

Views: 1895

Answers (1)

Rafael
Rafael

Reputation: 7746

You can certainly get the height of the parent when a child element is not displayed, but it sounds like you want to get the height of the parent when all of the children's heights are accounted. In this case, you can make the child(s) hidden but displayed, grab the height, and revert:

/* parentSelector: selector we wish to know its height
 * childSelector:  children to display when measuring parent
 */ 
function getHeight(parentSelector, childSelector) {
    var parent = $(parentSelector);
    var children = parent.children(childSelector);
    var styleState = [];

    //set state
    children.each(function (i) {
        let c = $(this);
        styleState[i] = c.css(['display', 'visibility']);
        c.css({ display: '', visibility: 'hidden' });
    });

    var height = parent.css('height');
    
    //revert state
    children.each(function (i) {
        let { display, visibility } = styleState[i];
        $(this).css({ display, visibility });
    });

    return height;
}

$('#test > div').hide();
console.log(getHeight('#test', 'div'));
#test { background: brown; padding: 1em }
#test > div { height: 50px; background: yellow; margin: 1em 0 }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<div id="test">
    <span>span</span>
    <div>div</div>
    <div>div</div>
</div>

I hope this helps!

Upvotes: 1

Related Questions