Get the sum of the outerHeight of all elements of the same class

$("selector") is already a collection. Access directly the .outerHeight() or any other method like .height()

var total = 0;
$("div").outerHeight(function(i, v){
   total += v;
});

alert( total ); // Just to test

var total = 0;

$("div").outerHeight(function(i, v){ total += v; });

alert( total );
div{background:#eee; margin:3px;}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div style="height:100px;">100px</div>
<div>just lots of breaklines :)<br><br><br><br></div>
<div style="height:200px;">200px</div>

Loop through each matching element and add up the outerheights:

var outerHeight = 0;
$('.profile').each(function() {
  outerHeight += $(this).outerHeight();
});
$("#total-height").text(outerHeight + 'px');

Here's the straight forward solution. Just loop through the elements of the jQuery object summing up the outerHeight()s.

var total = 0;
$('.profile').each(function(){
    total += $(this).outerHeight();
});
// total is good here

The important thing is that all jQuery getters only return the value of the first element in the jQuery set but you can add them yourself.

And here's a roundabout but cool way of doing it http://jsfiddle.net/mendesjuan/bKtAn/6/

// You can use a jQuery object as the `this` param in `Array.prototype` functions
var totalHeight = Array.prototype.reduce.call($('span'), function(a,b){
   // The first param is either the default value (passed into reduce)
   // or the result of the last call of this reducing function
   return a + $(b).outerHeight();
}, 0);

Which could be generalized as a reduce and made into a plugin like: http://jsfiddle.net/mendesjuan/bKtAn/9/

(function( $ ) {
    $.fn.reduce = function(cb, init) {  
      return Array.prototype.reduce.call(this, function(a,b){
            return cb(a, b);
      }, init);  
    }
})(jQuery);

const total = $('span').reduce(
   (accumulator, current) => accumulator + $(current).height(),
   0
);
console.log({total});

I think I went a bit overboard, sorry, I got excited, but these code snippets teach you a lot about JS and even a bit of jQuery

Tags:

Jquery