Here's a plain javascript function that will sort any set of tagged elements:
function sortElements(parentId, tagClass) {
var itemsToSort, p = document.getElementById(parentId);
if (p.getElementsByClassName) {
itemsToSort = p.getElementsByClassName(tagClass);
} else {
itemsToSort = getElementsByClassName(tagClass, "*", p);
}
// get all data into a sortable array
var data = [], order = [], item, placeHolder, i;
for (i = 0; i < itemsToSort.length; i++) {
item = itemsToSort[i];
// save position of item by inserting a placeholder right before it
placeHolder = document.createElement(item.tagName);
item.parentNode.insertBefore(placeHolder, item);
order.push(placeHolder);
// save item and text
data.push({obj: item, text: strTrim(item.innerHTML)});
}
// sort the item array by the text
data.sort(function(a, b) {
return(a.text.localeCompare(b.text));
});
// now reinsert items in sorted order
for (i = 0; i < data.length; i++) {
item = data[i].obj;
placeHolder = order[i];
// insert in new location
placeHolder.parentNode.insertBefore(item, placeHolder);
// remove placeholder
placeHolder.parentNode.removeChild(placeHolder);
}
}
function strTrim(str) {
return(str.replace(/^\s+/, "").replace(/\s+$/, ""));
}
// replacement for older versions of IE
function getElementsByClassName(className, tag, elm){
var testClass = new RegExp("(^|\\s)" + className + "(\\s|$)");
var tag = tag || "*";
var elm = elm || document;
var elements = (tag == "*" && elm.all)? elm.all : elm.getElementsByTagName(tag);
var returnElements = [];
var current;
var length = elements.length;
for(var i=0; i<length; i++){
current = elements[i];
if(testClass.test(current.className)){
returnElements.push(current);
}
}
return returnElements;
}
You can see it work here: http://jsfiddle.net/jfriend00/EztNw/. This demo shows it sorting the OP's table cells and an ordered list just to show that the function works on any set of elements.
The only limitation I'm aware of is that tagged elements cannot be children of other tagged elements. Works well for cells in a table.
This also uses getElementsByClassName()
so if older versions of IE are required, then a substitute/shim for that would be added (which is included in the jsFiddle).
Here's how this works:
- Get a list of all objects you want sorted
- Put a temporary placeholder object where each item is currently located so we know where to put things back in sorted order
- Build an array of the objects to be sorted and the sort key (text in this case)
- Sort that array
- Reinsert the sorted objects in the now sorted order, using the placeholder as a guide for where they go - remove the placeholder after it's slot is used