20

How can I get each element's width and sum them up?

For instance, here is the HTML:

<div id="container">
<div class="block-item" style="width:10px"></div>
<div class="block-item" style="width:50px"></div>
<div class="block-item" style="width:90px"></div>
<div>

I can think of looping through each element, but how do I sum the numbers up?

$('.block-item').each(function(index) {
    alert($(this).width());
});

I want to get the total number of 150 (10 + 50 + 90).

Thanks.

dda
  • 6,030
  • 2
  • 25
  • 34
Run
  • 54,938
  • 169
  • 450
  • 748

3 Answers3

30

Use parseInt(value, radix):

var totalWidth = 0;

$('.block-item').each(function(index) {
    totalWidth += parseInt($(this).width(), 10);
});

Here's an example fiddle.

no.good.at.coding
  • 20,221
  • 2
  • 60
  • 51
  • 1
    Probably want a += for the collector, yes? – Alex Mcp May 15 '11 at 01:49
  • @Alex Thank you, caught that dumb typo myself when I was creating the fiddle. – no.good.at.coding May 15 '11 at 01:52
  • 4
    10 is a radix. without it you could get unexpected results when parsing. this way you get base 10 result as opposed to octal. – vector Oct 26 '13 at 12:38
  • If you have the option to use [reduce()](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/Reduce) you could simplify this further by doing `$('.block-item').get().reduce(function(width, el){ return width + $(el).width() }, 0)` – Phil Cooper Jul 30 '15 at 14:55
2
var w = GetWidths('.block-item');

function GetWidths(id) {
    var i = 0;

    $(id).each(function (index) {
        i += parseInt($(this).width(), 10);
    });

    return i;
}
Igor Krupitsky
  • 787
  • 6
  • 9
0

for those people who have seen this thread recently: you can use jQuery map with ease:

var y = $('.block-item').map( function() {
    return $(this).width();
}).get()
.reduce((partialSum, a) => partialSum + a, 0);
console.log(y)
a.sadegh63
  • 56
  • 1
  • 8