Trying to sort tiles

Viewed 17

I just need it to sort divs on a page by the inner text. We have everything but the display functioning.

 var mylist = $('.ccl-tout-front');
 var listitems = mylist.sort((a,b)=> 
    $(a).text().localeCompare($(b).text()))
    $.each(listitems, function(idx, itm) { 
    mylist.append(itm); 
 });
1 Answers

You need to perform the append() after the sort, not within it. You also need to append to the parent() of the sorted elements. Try this:

let $mylist = $('.ccl-tout-front');
$mylist.sort((a, b) => $(a).text().localeCompare($(b).text())).appendTo($mylist.parent());
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div>
  <div class="ccl-tout-front">C</div>
  <div class="ccl-tout-front">D</div>
  <div class="ccl-tout-front">A</div>
  <div class="ccl-tout-front">E</div>
  <div class="ccl-tout-front">B</div>
</div>

Related