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

laukok picture laukok · May 15, 2011 · Viewed 28.8k times · Source

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.

Answer

no.good.at.coding picture no.good.at.coding · May 15, 2011

Use parseInt(value, radix):

var totalWidth = 0;

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

Here's an example fiddle.