The most efficient sorting method is to use the native Array.sort method ( jQuery().sort implements Array.sort ). Fiddle: http://jsfiddle.net/RJEJQ/1/ .
The code can become even more efficient by getting rid of jQuery and using document.createElement() and regular for() loops.
var originalUl = $('ul'); var listElements = originalUl.children('li'); //List listElements.sort(function(x, y){ return parseInt(x.textContent, 10) - parseInt(y.textContent); }); //Sorted by number, 1, 2, 3, ... var newList = $(""); //Placeholder listElements.each(function(i){ if(i%2 == 0){ //If even, a new list has to be created originalUl.before(newList); newList = $("<ul>"); //Create new list } newList.append(this); }); if(newList.length) { // If there are any remaining list elements in the holder. originalUl.before(newList); } originalUl.remove(); //Remove original, empty ul.
As you can see in this demonstration , the result is as follows:
ul li 1 li 3 ul li 4 li 5 ul li 7
source share