4

I have a set of DOM elements with data attributes. How can I get the maximum value?

<li data-for-something="1"></li>
<li data-for-something="1"></li>
<li data-for-something="2"></li>
<li data-for-something="3"></li>
<li data-for-something="4"></li>

I can use $('[data-some-value]') to get all the li with this attribute, and then loop through them. But I'm not sure what js or jquery methods are available to make this easier.

The best I've got is doing this:

function getMaxAttributeValue(attribute_name) {
  var max_value = 0;
  $('[' + attribute_name + ']').map(function(){
    var this_value = this.attr(attribute_name);
    if (this_value > max_value) {
      max_value = this_value;
    }
  });
  return max_value;
}
Don P
  • 60,113
  • 114
  • 300
  • 432

2 Answers2

1

I like this way:

function getMaxAttributeValue(attribute_name) {
  return Math.max.apply( Math, $('[' + attribute_name + ']').map(function(){
    return Number($(this).attr(attribute_name)) || -Infinity;
  }))
}

console.log(getMaxAttributeValue("data-for-something"))  // outputs 4
juvian
  • 15,875
  • 2
  • 37
  • 38
  • 1
    @DonnyP in case you have non-numeric attribute, will still work even if you have a li with `data-for-something="a"` – juvian Apr 25 '14 at 19:02
0

I think @juvian's answer is probably the best, however I fiddled around with this before I saw his answer, so I thought I'm going to share the way I wanted to do it. It's not a function, but works perfectly with your html structure. I made use of the dataset property.

var array = new Array;

$('li').each( function() { 
    array.push(parseInt($(this)[0].dataset.forSomething));
});

console.log(Math.max.apply(Math, array)); 

I added this to this fiddle: http://jsfiddle.net/vVkr6/

benomatis
  • 5,536
  • 7
  • 36
  • 59