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.
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
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>
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