Home > front end >  .height function returns false value
.height function returns false value

Time:03-24

I am trying to set dynamic height by getting element height and setting this on parent div but when I use jquery .height function returns the false value: For example:-

<div style="height: 300px">
    this is outer div
    <div style="position:absolute; height: 400px">
        this is inner div of which i need to read height and set to its parent
    </div>
</div>

my jquery code

var innerDiv = $("#innerDiv").height();
console.log(innerDiv);
//this is suppose to give 400 but on button click it show 845 and but on second click it shows 400
$("#outerDiv").css({'height': `${innerDiv}px`})

CodePudding user response:

You need id="innerDiv" on the inner div, as that is it’s reference id in your code.

<div style="height: 300px">
    this is outer div
    <div id="innerDiv" style="position:absolute; height: 400px">
        this is inner div of which i need to read height and set to its parent
    </div>
</div>

CodePudding user response:

There is nothing wrong in your code, except the missing IDs, in fact if you add id="outerDiv" and id="innerDiv" everything works well.

Maybe there is something else in your original script that stretches the inner div height to 845.

var innerDiv = $("#innerDiv").height();

console.log(innerDiv);
//this is suppose to give 400 but on button click it show 845 and but on second click it shows 400
$("#outerDiv").css({ height: `${innerDiv}px` });
div {
  /* a black outline to see the DIVs */
  outline: 1px solid black;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="outerDiv" style="height: 300px">
    this is outer div
    <div id="innerDiv" style="position:absolute; height: 400px">
        this is inner div of which i need to read height and set to its parent
    </div>
</div>

  • Related