jQuery: How to calculate the maximal attribute value of all matched elements?
I got another version:
var numbers = $(".a").map(function(){
return parseFloat(this.getAttribute('x')) || -Infinity;
}).toArray();
$("#max").html(Math.max.apply(Math, numbers));
This uses the map function to extract the values of the x-Attributes, converts the object into an array and provides the array elements as function parameters to Math.max
The Math.max trick was stolen from http://ejohn.org/blog/fast-javascript-maxmin/
UPDATE
add "|| -Infinity" to process the case correctly, when no attribute is present. See fiddle of @kubedan
Just loop over them:
var maximum = null;
$('.a').each(function() {
var value = parseFloat($(this).attr('x'));
maximum = (value > maximum) ? value : maximum;
});
Coming back to this with modern javascript:
let maxA = $(".a").get().reduce(function (result, item) {
return Math.max(result, $(item).attr("x"));
}, 0);