Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery: How to calculate the maximal attribute value of all matched elements?

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.

like image 507
Misha Moroshko Avatar asked Sep 23 '11 05:09

Misha Moroshko


People also ask

How to find max value in jQuery?

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.

How do I find my ATTR value?

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.

How do you find the element based on a data attribute value?

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.


2 Answers

Just loop over them:

var maximum = null;

$('.a').each(function() {
  var value = parseFloat($(this).attr('x'));
  maximum = (value > maximum) ? value : maximum;
});
like image 105
Blender Avatar answered Oct 11 '22 23:10

Blender


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

like image 41
topek Avatar answered Oct 11 '22 21:10

topek