Consider the following HTML:
<div class="a" x="6"></div>
<div class="a" x="9"></div>
<div class="a" x="2"></div>
...
<div class="a" x="8"></div>
How would you find the maximal x
value of all .a
elements ?
Assume that all x
values are positive integers.
Calculate the Max/Min value from a JS array using Math. max() and Math. min() functions and output the results in any element using jQuery.
The attr() method sets or returns attributes and values of the selected elements. When this method is used to return the attribute value, it returns the value of the FIRST matched element. When this method is used to set attribute values, it sets one or more attribute/value pairs for the set of matched elements.
Answer: Use the CSS Attribute Selector You can use the CSS attribute selectors to find an HTML element based on its data-attribute value using jQuery. The attribute selectors provide a very powerful way to select elements.
Just loop over them:
var maximum = null;
$('.a').each(function() {
var value = parseFloat($(this).attr('x'));
maximum = (value > maximum) ? value : maximum;
});
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With