If you already have the values in classes, jQuery already returns something that looks like an array, with all occurrences of that class ... The classic method to handle this is .each()
,
var tot = 0;
var n = 0;
$('.m').each(function(){
tot += parseInt( $(this).text() );
n++;
});
var MEDIA = tot/n;
However, for something as simple as calculating a mean, the ideal would really be to use an array, and this is also possible in jQuery, using the function makeArray()
,
var A = $.makeArray( $('.m') );
var Atot = 0;
for(i=0; i<A.length; i++)
Atot += parseInt(A[i].innerHTML);
var Amedia = Atot/A.length;
See link
NOTES
Javascript is not a language equipped with map / reduce to deal elegantly with arrays , but today, even with a small performance cost , it is already possible to make use of filter functions and aggregation of arrays. The average is a typical aggregate, and can be expressed with these features, see that other jsFiddle :
var A = $.makeArray( $('.m') ).map(function(a) {
return parseInt(a.innerHTML)
}); // ou $('.m').map(function(){ return parseInt($(this).html()) }).get();
var soma = A.reduce(function(a,b) {return a + b});
var media = soma / A.length;
This way of expressing an arrays algorithm is still little used, there are people who find it unintelligible, "mathematical thing" ... I try to avoid prejudices. You can, for example, use in formal specifications .
As for accessing the values of <input>
tags, the easiest thing in jQuery is .val
... For other tags (typically <span>
as exemplified in jsfiddle) using nodeValue can be faster, see link