Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 947
Run Avatar asked May 15 '11 01:05

Run


2 Answers

Use parseInt(value, radix):

var totalWidth = 0;

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

Here's an example fiddle.

like image 115
no.good.at.coding Avatar answered Sep 20 '22 05:09

no.good.at.coding


var w = GetWidths('.block-item');

function GetWidths(id) {
    var i = 0;

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

    return i;
}
like image 44
Igor Krupitsky Avatar answered Sep 23 '22 05:09

Igor Krupitsky