Fastest way to sort an unordered list's li elements / child nodes
Posted on 2006-04-27
I have a set of two lists with buttons to move items to and from each list. The element tree for each list looks like this:
My method for moving the elements works fine, but the problem is I also need to sort them after each transfer (The contents are strings).
Currently I do this by copying the UL's childNodes into a new array, sorting that array, deleting all nodes from the UL's childnodes, and copying the new ones in from the sorted clone array. This gets really slow with high numbers of elements (around 1000).
Basically I'd like suggestions or links to better algorithms for doing this.
Here's my sorting code, performed after items are transferred from one list to the other. dstObj is the UL that items were transferred to.
var x = new Array();
for(var j = 0; j < dstObj.childNodes.length; j++)
x[x.length] = dstObj.childNodes[j];
while(dstObj.childNodes.length > 0) dstObj.removeChild(dstObj.childNodes);
for(var k = 0; k < x.length; k++)
function itemOrder(a, b) //Sort function,
var aUp = a.innerText.toUpperCase();
var bUp = b.innerText.toUpperCase();
return ( aUp == bUp ? 0 : (aUp < bUp ? -1 : 1));