Sort the DIVs alphabetically without destroying or re-creating them?

I would 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 the button, they must be rearranged in alphabetical order. Obviously, there are several ways to do this, the most obvious is that we can get all the contents into an array, sort the array and recreate the HTML based on this.

This is an example of such a solution:

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

However, this would not play well with a lot of the code that was already in use, and I was hoping I could just move the divs without doing anything destructive. Is it possible?

+7
javascript jquery
source share
3 answers

 $('.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> 
+11
source share

Use append.

 var $divs = $("div.box"); $("div.box").on("click", function (e) { alert("I'm an original"); }); $('#alphBnt').on('click', function () { var alphabeticallyOrderedDivs = $divs.sort(function (a, b) { return $(a).find("h1").text() > $(b).find("h1").text(); }); alphabeticallyOrderedDivs.each(function (i, item) { $("#container").append(item); }); }); $('#numBnt').on('click', function () { var numericallyOrderedDivs = $divs.sort(function (a, b) { return $(a).find("h2").text() > $(b).find("h2").text(); }); numericallyOrderedDivs.each(function (i, item) { $("#container").append(item); }); }); 

Fiddle

+1
source share

Can be done quite simply even without jQuery

 function sortThem(s) { Array.prototype.slice.call(document.body.querySelectorAll(s)).sort(function sort (ea, eb) { var a = ea.textContent.trim(); var b = eb.textContent.trim(); if (a.textContent < b.textContent) return -1; if (a.textContent > b.textContent) return 1; return 0; }).forEach(function(div) { div.parentElement.appendChild(div); }); } // call it like this sortThem('div.sortme'); 

the .appendChild (x) element adds x as the last child of the element , if x exists in the DOM, it moves from its current location, so no gymnastics needs to remove it in one place and add it to another

+1
source share

All Articles