4

how do I select all the divs inside another div and find the greatest 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 the div that's having the greatest id attribute

I use the following code to grab the id attribute:

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

But that returns the latest one, not the greatest.

Roko C. Buljan
  • 196,159
  • 39
  • 305
  • 313
Akar
  • 5,075
  • 2
  • 25
  • 39

3 Answers3

6
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/ used to return a new Array of the desired values.
How might I find the largest number contained in a JavaScript array? is used for the rest.

The unary + is used to convert any possible String number to Number.
To prevent a NaN resulting a mismatch caused by a mistakenly inserted Alpha character you can use:

return +this.dataset.id || 0; // Prevent NaN and turn "a" to 0
Community
  • 1
  • 1
Roko C. Buljan
  • 196,159
  • 39
  • 305
  • 313
2

If you like underscore, this can be done as follows with the max function.

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>
Frank Bryce
  • 8,076
  • 4
  • 38
  • 56
0

In my opinion, cleaner than tracking the value and doing comparisons on your own. Simply push the values to an Array and use Math to determine the max.

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

http://jsfiddle.net/d0wuxygs/

For reference: Get max and min value from array in JavaScript

Community
  • 1
  • 1
Tristan Lee
  • 1,210
  • 10
  • 17