1
\$\begingroup\$

I am summing the total .outerHeight() of multiple divs 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();
Jamal
35.2k13 gold badges134 silver badges238 bronze badges
asked May 23, 2013 at 8:22
\$\endgroup\$

2 Answers 2

2
\$\begingroup\$

You'll have to add a class to the divs 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()
});
answered May 23, 2013 at 9:42
\$\endgroup\$
1
\$\begingroup\$

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.

answered May 24, 2013 at 14:01
\$\endgroup\$

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.