jQuery: get each element's width and sum them up
Asked Answered
S

3

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.

Scapula answered 15/5, 2011 at 1:46 Comment(0)
A
30

Use parseInt(value, radix):

var totalWidth = 0;

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

Here's an example fiddle.

Aixlachapelle answered 15/5, 2011 at 1:48 Comment(4)
Probably want a += for the collector, yes?Mammillate
@Alex Thank you, caught that dumb typo myself when I was creating the fiddle.Aixlachapelle
10 is a radix. without it you could get unexpected results when parsing. this way you get base 10 result as opposed to octal.Rhodian
If you have the option to use reduce() you could simplify this further by doing $('.block-item').get().reduce(function(width, el){ return width + $(el).width() }, 0)Podophyllin
C
2
var w = GetWidths('.block-item');

function GetWidths(id) {
    var i = 0;

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

    return i;
}
Chuppah answered 24/5, 2016 at 4:41 Comment(1)
Clean and elegant usage of variables and functions passed between each other.Millenarian
P
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)
Phonology answered 23/2, 2023 at 10:57 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.