Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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;
}).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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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>
</div>
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading