Sum using jQuery each function without global variable

each, jquery

Solution

If you don't want to introduce a global variable, you could use something like this:

$("#total_forces").html(function() {
    var a = 0;
    $(".force").each(function() {
        a += parseInt($(this).html());
    });
    return a;
});

Problem

I want to add some HTML elements that have the same class name. So, the code will be like this with jQuery. ``` $(".force").each(function (){ a += parseInt( $(this).html()); }); $("#total_forces").html(a); ``` In this code, the variable has to be global. Is there any other elegant way to sum every `.force` value and get the sum out of the `each` function without global variable?

Original source