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.
Basically, $(window). height() give you the maximum height inside of the browser window (viewport), and $(document). height() gives you the height of the document inside of the browser. Most of the time, they will be exactly the same, even with scrollbars.
Method 1: The height() method returns the first matched element's height, But the height(value) method sets all matched elements height. // Returns the height of the first matched element $(selector). height() // Set the height of the all matched elements $(selector). height(value);
The children() method returns all direct children of the selected element. The DOM tree: This method only traverse a single level down the DOM tree. To traverse down multiple levels (to return grandchildren or other descendants), use the find() method.
jQuery height() Method The height() method sets or returns the height of the selected elements. When this method is used to return height, it returns the height of the FIRST matched element.
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 love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With