Unfortunately a list of html nodes (NodeList) in Javascript does not have a sort
method, otherwise you could apply that directly. However, if you transform it into an array, you can sort it easily by content and then append it back to the list. On balance I'm not sure this is really better than your original solution though!
var myListParent = document.getElementById('list');
myListChildren = myListParent.children,
myListArray = [];
for (var i = 0; i < myListChildren.length; i++) {
myListArray.push(myListChildren[i]);
}
function sortByInnerHTML(a, b) {
var h1 = a.innerHTML,
h2 = b.innerHTML;
if (h1 == h2) return 0;
else if (h1 < h2) return -1;
else return 1;
}
myListArray.sort(sortByInnerHTML);
for (var i = 0; i < myListArray.length; i++) {
myListParent.appendChild(myListArray[i]);
}
(jsfiddle)
However, to make your code neater and more reusable you could create some functions here.
function sortHTML(parent) {
var a = [], children = parent.children;
for (var i = 0; i < children.length; i++) {
a.push(children[i]);
}
a.sort(sortBy('innerHTML'));
for (var i = 0; i < a.length; i++) {
parent.appendChild(a[i]);
}
}
function sortBy(p) {
return function(a, b) {
return a[p] < b[p] ? -1 : a[p] > b[p];
}
}
sortHTML(document.getElementById('list'));
http://jsfiddle.net/DL7Xa/2/