Jquery Find, Sort and then Append only specific 'N' numbers child element

I am finding child elements from the parent element and sorting them and then adding them on the parent element again:

$('#parentElement').find('.childElement').sort(function(a, b) {
    var contentA = parseInt($(a).attr('data-name'));
    var contentB = parseInt($(b).attr('data-name'));
    return (contentA < contentB) ? 1 : (contentA > contentB) ? -1 : 0;

But I want to append only the first 5 sorted child elements on the parent element. I don’t want to append all child elements. Any solution?

>Solution :

To get the first 5 sorted elements from that collection you can use .slice(). Also note that the code can be made more succinct by using data() to retrieve the attributes (as this will negate the need to manually call parseInt()) and also by combining the original selectors:

$('#parentElement .childElement').remove().sort((a, b) => {
  var contentA = $(a).data('name');
  var contentB = $(b).data('name');
  return (contentA < contentB) ? 1 : (contentA > contentB) ? -1 : 0;
}).slice(0, 5).appendTo('#parentElement');
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.0/jquery.min.js"></script>
<div id="parentElement">
  <div class="childElement" data-name="1">1</div>
  <div class="childElement" data-name="9">9</div>
  <div class="childElement" data-name="4">4</div>
  <div class="childElement" data-name="10">10</div>
  <div class="childElement" data-name="3">3</div>
  <div class="childElement" data-name="6">6</div>
  <div class="childElement" data-name="5">5</div>
  <div class="childElement" data-name="8">8</div>
  <div class="childElement" data-name="2">2</div>
  <div class="childElement" data-name="7">7</div>

Leave a Reply