I am summing the total .outerHeight()
of multiple div
s like this:
var h = $('#div1').outerHeight() + $('#div2').outerHeight() + $('#div3').outerHeight() + $('#div4').outerHeight();
Is there any way to do this more efficiently?
I was considering something like this (but it doesn't work):
$('#div1, #div2, #div3').outerHeight();
2 Answers 2
You'll have to add a class to the div
s to be able to select them all
<div id="div1" class="sumdiv"></div>
<div id="div2" class="sumdiv"></div>
Then, use $.each()
(http://api.jquery.com/each/)
var sum = 0;
$( ".sumdiv" ).each(function( index ) {
sum += $(this).outerHeight()
});
A more functional approach, but it requires the browser to support .reduce()
var sum = $('#div1, #div2, #div3').map(function () {
return $(this).outerHeight();
}).get().reduce(function (sum, value) {
return sum + value;
}, 0);
Or
var sum = $('#div1, #div2, #div3').get().reduce(function (sum, element) {
return sum + $(element).outerHeight();
}, 0);
Alternatively, for cross-browser support, you can use underscore.js
var sum = _.reduce($('#div1, #div2, #div3').get(), function (sum, element) {
return sum + $(element).outerHeight();
}, 0);
But Topener's answer is straightforward, so you might as well go with that.