Legarndary
Legarndary

Reputation: 967

Jquery add attributes of child elements

I have an <ul> list where all the children <li> have an "home-made" attribute of size like this:

<ul class="container">
    <li size="3"></li>
    <li size="5"></li>
    <li size="2"></li>
</ul>

How do I get the size value of all the children and then add them to, so i end up with a variable that is equal to (in this case) 10?
The number of children and the size number is dynamic, so I am guessing that I need some kind of loop?

Upvotes: 2

Views: 5401

Answers (4)

Amit
Amit

Reputation: 15387

Try this

$(function(){
    var sum = 0;
    $(".container>li[size]").each(function(){
        var p = parseInt($(this).attr('size'));
        sum += p;
    });
    alert(sum);
});

DEMO

Upvotes: 0

Milind Anantwar
Milind Anantwar

Reputation: 82231

You mean this:

var sum = 0;
$('.container li').each(function() {
var p = parseInt($(this).prop('size'));
sum += p;
});
alert(sum);

Working Fiddle

Upvotes: 0

VisioN
VisioN

Reputation: 145368

Here is the simplest way:

var sum = 0;

$('.container li').each(function() {
    sum += +$(this).attr('size');
});

console.log(sum);

Here is a more complicated way for modern browsers:

var sum = $('.container li').map(function() {
    return +$(this).attr('size');
}).get().reduce(function(a, b) {
    return a + b;
});

console.log(sum);

Upvotes: 7

Rajaprabhu Aravindasamy
Rajaprabhu Aravindasamy

Reputation: 67197

Try,

var sum = 0;

$('.container li[size]').each(function(){
  sum += +$(this).attr('size');
});

console.log(sum);

Note : To be frank, i just copied the summing stuff from VisioN's Answer.

Upvotes: 1

Related Questions