Emily Emily - 1 month ago 14
Javascript Question

Get higher value id of list in jquery

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!

Answer

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>

Comments