2 * jQuery.fn.sortElements
\r
4 * @author James Padolsey (http://james.padolsey.com)
\r
6 * @updated 18-MAR-2010
\r
8 * @param Function comparator:
\r
9 * Exactly the same behaviour as [1,2,3].sort(comparator)
\r
11 * @param Function getSortable
\r
12 * A function that should return the element that is
\r
13 * to be sorted. The comparator will run on the
\r
14 * current collection, but you may want the actual
\r
15 * resulting sort to occur on a parent or another
\r
16 * associated element.
\r
18 * E.g. $('td').sortElements(comparator, function(){
\r
19 * return this.parentNode;
\r
22 * The <td>'s parent (<tr>) will be sorted instead
\r
23 * of the <td> itself.
\r
25 jQuery.fn.sortElements = (function(){
\r
29 return function(comparator, getSortable) {
\r
31 getSortable = getSortable || function(){return this;};
\r
33 var placements = this.map(function(){
\r
35 var sortElement = getSortable.call(this),
\r
36 parentNode = sortElement.parentNode,
\r
38 // Since the element itself will change position, we have
\r
39 // to have some way of storing it's original position in
\r
40 // the DOM. The easiest way is to have a 'flag' node:
\r
41 nextSibling = parentNode.insertBefore(
\r
42 document.createTextNode(''),
\r
43 sortElement.nextSibling
\r
48 if (parentNode === this) {
\r
50 "You can't sort elements if any one is a descendant of another."
\r
54 // Insert before flag:
\r
55 parentNode.insertBefore(this, nextSibling);
\r
57 parentNode.removeChild(nextSibling);
\r
63 return sort.call(this, comparator).each(function(i){
\r
64 placements[i].call(getSortable.call(this));
\r