Reputation: 312
I have a list:
<ul id="testList">
<li id="3"></li>
<li id="2"></li>
<li id="1"></li>
</ul>
I need get to higher value id of li element with jQuery. In this example it would be, 3. Then append class "last". I tried with each function but don't work.
$('#testList li').each(function(index, li){
//Here obtain a higher value id
$('#testList li').last().addClass('last');
});
I hope someone can help me. Thank you very much! Regards!
Upvotes: 0
Views: 867
Reputation: 122037
You can use Math.max
and map()
to get maximum id value and then addClass()
var h = Math.max.apply(null, $('#testList li').map(function() {
return $(this).attr('id');
}))
$('#' + h).addClass('last');
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul id="testList">
<li id="3"></li>
<li id="2"></li>
<li id="1"></li>
</ul>
Upvotes: 3
Reputation: 26160
Probably not the most efficient way, but this would do it:
// initialize the max value to a low number
var max = 0;
// iterate over each li item in the list
$('#testList li').each(function() {
// ensure we have a number
var id = parseInt($(this).prop('id'));
if (! isNaN(id)) {
max = Math.max(max, id);
}
});
// Given that max contains an ID, just pass that in to the selector to add class
$('#' + max).addClass('last');
Upvotes: 0