Find the largest numerical attribute

how to select all divs inside another div and find the largest id attribute?

Consider the following code:

<div class="posts">
    <div class="post" data-id="5"></div>
    <div class="post" data-id="3"></div>
    <div class="post" data-id="1"></div>
    <div class="post" data-id="4"></div>
</div>    

What I want to do is find divwhich has the largestid attribute

I use the following code to capture id attribute:

$('.posts .post').data('id');

But this returns the last , not the largest .

+4
source share
3 answers
var max = 0;
$('.post').attr("data-id", function(i,v){
   max = +v > max ? +v : max;
});

console.log( max ); // 5

Another way:

var ids = $('.post').map(function(){
   return +this.dataset.id;            // or use jQ: return +$(this).data('id');
});

console.log( Math.max.apply(Math, ids) ); // 5

http://api.jquery.com/jquery.map/ is used to return a new array of desired values.
How can I find the largest number contained in a JavaScript array? used for the rest.

+ Number.
NaN, , Alpha, :

return +this.dataset.id || 0; // Prevent NaN and turn "a" to 0
+6

underscore, : max.

var getIdAttr = function(el){ return el.getAttribute('data-id'); };
var elementIds = _.map($('.post'), getIdAttr);
var maxId = _.max(elementIds);

console.log(maxId); // 5
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/underscore.js/1.6.0/underscore-min.js"></script>
<div class="posts">
  <div class="post" data-id="3"></div>
  <div class="post" data-id="5"></div>
  <div class="post" data-id="1"></div>
  <div class="post" data-id="4"></div>
</div>
Hide result
+2

-, , . Math .

var max = Math.max.apply(Math, $(".posts .post").map(function () {
    return $(this).data("id");
}));

http://jsfiddle.net/d0wuxygs/

: JavaScript

0
source

All Articles