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.
Author by
plewas
Updated on June 04, 2022Comments
-
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?
-
Barlas Apaydin almost 12 yearsdo you want to learn height div class="a" ? or b?
-
nbrooks almost 12 years
-
-
spinningarrow almost 12 yearsSince the question says "in each div class set to a", that selector should be
$('.a').find('.b')
. -
nbrooks almost 12 years@spinningarrow or simply
$('.a > .b')
-
James Allardice almost 12 yearsRe-reading the question, I think the OP actually wants separate results, one for each
.a
element. I'll update my answer. -
plewas almost 12 yearsIt works great, but how to set local maximum height for each class b in clas a? Alert shows a correct value.
-
billyonecan almost 12 yearsJust add
$('.b', this).height(maxHeight)
(where thealert
currently is) - working fiddle: jsfiddle.net/RZzTv -
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 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 over 9 yearsThanks for inspiration. +1