Javascript Sorter for HTML lists
Posted: Thu Jan 22, 2009 8:50 pm
The problem description:
Write a function in Javascript to sort <li>'s lexicographically on the linked text they contain. It came up for a client using Serena Collage (R.I.P.) for content management. Long story short, they need their autogenerated subnavigation links to be alphabetized and doing it on the server side was not an option due to their environment.
My solution works fine in Firefox, Safari, IE6, & IE7, but basically I'm posting this because I'm inexperienced doing anything but really simple DOM stuff in Javascript and am hoping someone will come along school me to how I should have approached it.
My solution:
See it in action at: http://oneorangesoftware.com/connor/misc/sorter.html
Any comments would be greatly appreaciated, thanks for reading!
Write a function in Javascript to sort <li>'s lexicographically on the linked text they contain. It came up for a client using Serena Collage (R.I.P.) for content management. Long story short, they need their autogenerated subnavigation links to be alphabetized and doing it on the server side was not an option due to their environment.
My solution works fine in Firefox, Safari, IE6, & IE7, but basically I'm posting this because I'm inexperienced doing anything but really simple DOM stuff in Javascript and am hoping someone will come along school me to how I should have approached it.
My solution:
See it in action at: http://oneorangesoftware.com/connor/misc/sorter.html
Code: Select all
function sortUL(listName) {
var targetList = document.getElementById(listName);
var listItems = targetList.childNodes;
// remove extraneous array elements
var tempArr = Array();
var i;
for (i=0; i<listItems.length; i++) {
if (listItems[i].innerHTML != null) {
var ndx = tempArr.length;
tempArr[ndx] = listItems[i];
}
}
listItems = tempArr;
listItems.sort(function sortListItemsBy(item1, item2) {
var item1Text, item2Text, j;
for (j=0; j<item1.childNodes.length; j++) {
if (item1.childNodes[j].innerHTML != null) {
item1Text = item1.childNodes[j].innerHTML;
break;
}
}
for (j=0; j<item2.childNodes.length; j++) {
if (item2.childNodes[j].innerHTML != null) {
item2Text = item2.childNodes[j].innerHTML;
break;
}
}
if (item1Text > item2Text)
return 1;
else
return -1;
});
var newListHTML = "";
for (i=0; i<listItems.length; i++) {
newListHTML = newListHTML+"<li>"+listItems[i].innerHTML+"<\/li>";
}
targetList.innerHTML = newListHTML;
}