jQuery .each and height of div

13,432

Solution 1

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

Solution 2

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.

Share:
13,432
plewas
Author by

plewas

Updated on June 04, 2022

Comments

  • plewas
    plewas almost 2 years

    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?

  • spinningarrow
    spinningarrow almost 12 years
    Since the question says "in each div class set to a", that selector should be $('.a').find('.b').
  • nbrooks
    nbrooks almost 12 years
    @spinningarrow or simply $('.a > .b')
  • James Allardice
    James Allardice almost 12 years
    Re-reading the question, I think the OP actually wants separate results, one for each .a element. I'll update my answer.
  • plewas
    plewas almost 12 years
    It works great, but how to set local maximum height for each class b in clas a? Alert shows a correct value.
  • billyonecan
    billyonecan almost 12 years
    Just add $('.b', this).height(maxHeight) (where the alert currently is) - working fiddle: jsfiddle.net/RZzTv
  • spinningarrow
    spinningarrow almost 12 years
    @nbrooks: Well, yes. However, Sizzle works from right to left and the child selector is actually about 70% slower than using .find(). This place has some pretty good information on jQuery performance.
  • nbrooks
    nbrooks almost 12 years
    @spinningarrow Thanks for that link, didn't know that. I just figured the css selectors always outperformed the jQuery methods that didn't rely on native methods. Good to know!
  • Severe Torture
    Severe Torture over 9 years
    Thanks for inspiration. +1