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

Time:06-16

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;
}).appendTo('#parentElement');

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?

CodePudding user response:

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  data-name="1">1</div>
  <div  data-name="9">9</div>
  <div  data-name="4">4</div>
  <div  data-name="10">10</div>
  <div  data-name="3">3</div>
  <div  data-name="6">6</div>
  <div  data-name="5">5</div>
  <div  data-name="8">8</div>
  <div  data-name="2">2</div>
  <div  data-name="7">7</div>
</div>

  • Related