'jQuery .height() function returns false value
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`})
Solution 1:[1]
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>
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | DanieleAlessandra |
