Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
103
rated 0 times [  105] [ 2]  / answers: 1 / hits: 18853  / 9 Years ago, tue, july 7, 2015, 12:00:00

I'd like to be able to sort a bunch of div elements on my page with the click of a button.



All of them have simple text content, for example:



<div class='sortme'>
CCC
</div>
<div class='sortme'>
AAA
</div>
<div class='sortme'>
BBB
</div>
<div class='sortme'>
DDD
</div>


When the user clicks a button, they should be rearranged in alphabetical order. Obviously there's a number of ways to do this, most obviously we can get all the contents into an array, sort the array and recreate the HTML based on that.



This is an example of such a solution:



http://jsfiddle.net/hibbard_eu/C2heg/



However, this wouldn't play nice with a lot of code already being used, and I was hoping to be able to simply move the divs around without doing anything destructive. Is this possible?


More From » jquery

 Answers
11

  1. Sort the element array with sort()

  2. Reattach(in their sorted state) with appendTo()





$('.sortme').sort(function(a, b) {
if (a.textContent < b.textContent) {
return -1;
} else {
return 1;
}
}).appendTo('body');

<script src=https://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js></script>
<div class='sortme'>
CCC
</div>
<div class='sortme'>
AAA
</div>
<div class='sortme'>
BBB
</div>
<div class='sortme'>
DDD
</div>




[#65901] Saturday, July 4, 2015, 9 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
ninaemiliaj

Total Points: 405
Total Questions: 112
Total Answers: 112

Location: Gabon
Member since Sat, Jul 25, 2020
4 Years ago
;