0

I'm using the following html/jquery to re-order the child elements of a containing div, based on their data-price attribute.

<div id="parent_div">
 <div class="child_div" data-price="102">Item x</div>
 <div class="child_div" data-price="95">Item y</div>
 <div class="child_div" data-price="210">Item z</div>
</div>

The HTML is populated by multiple AJAX calls and so the initial results are not ordered, and could number 50+ child elements. Once the AJAX calls are complete and HTML populated, I am running the following jquery:

function giveFormatOrder(parent_div, child_div) {

 var $wrapper = $(parent_div);

 $wrapper.find(child_div).sort(function(a, b) {
  return +a.getAttribute('data-price') - +b.getAttribute('data-price');
 })
 .appendTo($wrapper);
}

giveFormatOrder('#parent_div','.child_div');

This works fine. But I would like to hide all but the first 10 ordered child elements. Is there a way I can modify the jquery function to achieve this, by adding a counter and adding a show/hide class? Or do I need to trigger a second function once the sort is complete? I'm looking for the most performant approach possible but am not sure how to go about it.

Paul
  • 661
  • 4
  • 12
  • 22

2 Answers2

1

You can do it by using .slice(10).hide();

Demo

The demo only show the 2 first.

function giveFormatOrder(parent_div, child_div) {

  var $wrapper = $(parent_div);

  $wrapper.find(child_div).sort(function(a, b) {
      return +a.getAttribute('data-price') - +b.getAttribute('data-price');
    })
    .appendTo($wrapper).slice(2).hide();
}

giveFormatOrder('#parent_div', '.child_div');
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="parent_div">
  <div class="child_div" data-price="102">Item x</div>
  <div class="child_div" data-price="95">Item y</div>
  <div class="child_div" data-price="210">Item z</div>
</div>
Carsten Løvbo Andersen
  • 26,637
  • 10
  • 47
  • 77
1

By slice and append using jquery.

Note: The hidden children not available in DOM

function giveFormatOrder(parent_div, child_div) {
  var $wrapper = $(parent_div);

  $wrapper.find(child_div).detach().sort(function(a, b) {
      return $(a).data('price') - $(b).data('price');
    }).slice(0, 3).appendTo($wrapper);
}

giveFormatOrder('#parent_div', '.child_div');
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<div id="parent_div">
  <div class="child_div" data-price="102">Item x 102</div>
  <div class="child_div" data-price="95">Item y 95</div>
  <div class="child_div" data-price="210">Item z 210</div>
  <div class="child_div" data-price="110">Item z 110</div>
  <div class="child_div" data-price="10">Item z 10</div>
  <div class="child_div" data-price="140">Item z 140</div>
</div>
User863
  • 19,346
  • 2
  • 17
  • 41