Consider the following HTML:
var max = null;
$('.a').each(function() {
var x = +($(this).attr('x'));
if (max === null || x > max)
max = x;
}
alert(max === null ? "No matching elements found" : "The maximum is " + max);
Note the unary +
operator to convert the attribute to a number. You may want to add some error checking to ensure it actually is a number - and that the attribute exists at all. You could change the selector to only select elements with the class and the attribute: $('.a[x]')
.
var max =0;
$('.a').each(function(){
if(parseFloat($(this).attr('x'))>max)
{
max = parseFloat($(this).attr('x')) ;
}
});
alert(max);
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
You could also use Array.sort in jQuery, as explained here then use $('.a:last') to get the selected element.
Just loop over them:
var maximum = null;
$('.a').each(function() {
var value = parseFloat($(this).attr('x'));
maximum = (value > maximum) ? value : maximum;
});
I was doing some tests regarding this topic, and if performance matters, a old but gold simple for
would be better than jQuery.map()
, Math.apply()
and also Array.sort()
:
var items = $(".a");
for (var i = 0; i < items.length; i++) {
var val = items.eq(i).prop('x');
if (val > max) max = val;
}
Here are the jsperf tests: http://jsperf.com/max-value-by-data-attribute. Nothing really drastic, but interesting anyway.