Calculate height of div's children using jQuery

Try it like so:

var totalHeight = 0;

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

http://api.jquery.com/outerHeight/ takes margins, paddings and borders into the calculation which should return a more reliable result.


Another approach is calculating the distance between the top- and bottommost offsets within the element, which would account for any non-static positioned elements.

I've only tested this in one page and environment, so I'm not at all sure how safe it is to use. Please post a comment if be very bad codes or if it deserves some improvement.

var topOffset = bottomOffset = 0,
    outer = true;
$el.children().each(function(i, e){
    var $e = $(e),
        eTopOffset = $e.offset().top,
        eBottomOffset = eTopOffset + (outer ? $e.outerHeight() : $e.height());

    if (eTopOffset < topOffset) {
        topOffset = eTopOffset;
    }
    if (eBottomOffset > bottomOffset) {
        bottomOffset = eBottomOffset;
    }
});

var childrenHeight = bottomOffset - topOffset - $el.offset().top;

If you want to ignore hidden elements, you can filter them out:

$("#leftcolumn").children().filter(':visible').each(function(){
    totalHeight += $(this).outerHeight();
});

Tags:

Jquery