lshettyl lshettyl - 7 months ago 47
Javascript Question

element with the max height from a set of elements

I have a set of

div
elements. In
jQuery
, I would like to be able to find out the
div
with the maximum height and also the height of that
div
. For instance:

<div>
<div class="panel">
Line 1
Line 2
</div>
<div class="panel">
Line 1<br/>
Line 2<br/>
Line 3<br/>
Line 4<br/>
</div>
<div class="panel">
Line 1
</div>
<div class="panel">
Line 1
Line 2
</div>
</div>


By looking at the above, we know that the 2nd
div
(with 4 Lines) has the maximum height of all. How do I find this out? Could someone please help?

So far I've tried:

$("div.panel").height()
which returns the height of the 1st
div
.

Answer

Use .map() and Math.max.

var maxHeight = Math.max.apply(null, $("div.panel").map(function ()
{
    return $(this).height();
}).get());

If that's confusing to read, this might be clearer:

var heights = $("div.panel").map(function ()
    {
        return $(this).height();
    }).get(),

    maxHeight = Math.max.apply(null, heights);
Comments