--- /dev/null
+/**\r
+ * jQuery.fn.sortElements\r
+ * --------------\r
+ * @author James Padolsey (http://james.padolsey.com)\r
+ * @version 0.11\r
+ * @updated 18-MAR-2010\r
+ * --------------\r
+ * @param Function comparator:\r
+ * Exactly the same behaviour as [1,2,3].sort(comparator)\r
+ * \r
+ * @param Function getSortable\r
+ * A function that should return the element that is\r
+ * to be sorted. The comparator will run on the\r
+ * current collection, but you may want the actual\r
+ * resulting sort to occur on a parent or another\r
+ * associated element.\r
+ * \r
+ * E.g. $('td').sortElements(comparator, function(){\r
+ * return this.parentNode; \r
+ * })\r
+ * \r
+ * The <td>'s parent (<tr>) will be sorted instead\r
+ * of the <td> itself.\r
+ */\r
+jQuery.fn.sortElements = (function(){\r
+ \r
+ var sort = [].sort;\r
+ \r
+ return function(comparator, getSortable) {\r
+ \r
+ getSortable = getSortable || function(){return this;};\r
+ \r
+ var placements = this.map(function(){\r
+ \r
+ var sortElement = getSortable.call(this),\r
+ parentNode = sortElement.parentNode,\r
+ \r
+ // Since the element itself will change position, we have\r
+ // to have some way of storing it's original position in\r
+ // the DOM. The easiest way is to have a 'flag' node:\r
+ nextSibling = parentNode.insertBefore(\r
+ document.createTextNode(''),\r
+ sortElement.nextSibling\r
+ );\r
+ \r
+ return function() {\r
+ \r
+ if (parentNode === this) {\r
+ throw new Error(\r
+ "You can't sort elements if any one is a descendant of another."\r
+ );\r
+ }\r
+ \r
+ // Insert before flag:\r
+ parentNode.insertBefore(this, nextSibling);\r
+ // Remove flag:\r
+ parentNode.removeChild(nextSibling);\r
+ \r
+ };\r
+ \r
+ });\r
+ \r
+ return sort.call(this, comparator).each(function(i){\r
+ placements[i].call(getSortable.call(this));\r
+ });\r
+ \r
+ };\r
+ \r
+})();
\ No newline at end of file