Calculate height of div's children using jQuery

Viewed 45023

I want to match parent's height with the total height of its' children, so the content does not flow out from parent's border. I'm using the following code :

 $("#leftcolumn").each(function(){
     totalHeight=totalHeight+$(this).height();
  });

Will it iterate through all the div's children? Sometimes, it works sometimes it doesn't.

Also, I tried following code, assuming it will consider all its children. But the result is strange and gives doubled height from the correct result.

 $("#leftcolumn > *").each(function(){
   totalHeight=totalHeight+$(this).height();
 });

Thanks in advance.

5 Answers

How about like this. Does not require you to mutate a variable in an outer scope, allows you to reuse the sumHeights function.

function sumHeights(height, element) {
    return height + $(element).outerHeight(true);
}

const outerHeight = $('#leftcolumn')
    .children()
    .toArray()
    .reduce(sumHeights, 0);
Related