Dr3am3rz Dr3am3rz - 7 months ago 34
Javascript Question

Get children element height in separate div

I would like to get the child elements of each div and then set the height of each div according to their respective total child elements height.

I tried to find a similar question but can't find what I wanted. I know I needed an .each function but I can't get it to work.

Below is my code :

HTML

<ul>
<li>
<div class="container">
<h1>content</h1>
<a href="#">content</a>
</div>
</li>
<li>
<div class="container">
<h1>very long contents</h1>
<p>content</p>
<a href="#">content</a>
</div>
</li>
<li>
<div class="container">
<h1>super uber ultra long contents</h1>
<p>content</p>
<a href="#">content</a>
</div>
</li>
</ul>


jQuery

$("ul li").each(function() {
$("ul li div").each(function(){
var div_ht = 0;
$("ul li div").children().each(function() {
div_ht += $(this).outerHeight(true);
});
$("ul li div").height(div_ht);
});
});


What I want to achieve is let's say the 1st div's child element's total height is 100px, then it will set the 1st div to 100px height. If the 2nd div's child element's total height is 300px, then it will set the 2nd div to 300px height.

Answer

try

$("ul li").each(function() {
    $(this).find("div").each(function(){ //this line changed, iterating individual li's div rather than whole bunch
        var div_ht = 0;
        $(this).children().each(function() { //observe change in this line too
            div_ht += $(this).outerHeight(true);
        });
        $(this).height(div_ht); //observe change in this line too
    });
});

Also, if you simply want to set the height of div as the sum on their children height, then simply set the height of those div to auto

$("ul li div").css("height", "auto");
Comments