plewas
plewas

Reputation: 248

jQuery .each and height of div

I have construction like this:

<div class="a">
  <div class="b"></div>
  <div class="b"></div>
 <div class="b"></div>
 <div class="b"></div>
</div>
<div class="a">
  <div class="b"></div>
  <div class="b"></div>
</div>
<div class="a">
  <div class="b"></div>
  <div class="b"></div>
  <div class="b"></div>
</div>

I would like to find the highest div with class set to b in each div class set to a, and display in alert?

Upvotes: 2

Views: 14135

Answers (2)

James Allardice
James Allardice

Reputation: 166061

You can use .map() to produce a jQuery object (in this case it is effectively an array of numbers) containing the height of each matching element. You can then apply that array to Math.max to determine the largest value in it:

var maxHeight = Math.max.apply(Math, ​$(".b").map(function () {
    return $(this).height(); 
}));

Here's a working example.


Update (this one should behave exactly as you specify in your question)

$("div.a").each(function () {
    alert(Math.max.apply(Math, ​$("div.b", this).map(function () {
        return $(this).height(); 
    })));
});

Here's another working example.

Upvotes: 6

billyonecan
billyonecan

Reputation: 20270

$('.a').each(function() {
    var maxHeight = 0;
    $('.b', this).each(function() {
        if($(this).height() > maxHeight) {
         maxHeight = $(this).height();  
        }
    });
    alert(maxHeight);
});

Upvotes: 7

Related Questions