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();
\$\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()
});
\$\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.

\$\endgroup\$

You must log in to answer this question.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.