There are quite a few table-sorting functions/plugins out there, but I’ve yet to find something sufficiently low-level for general element-sorting. What I wanted was a simple jQuery plugin that would take a sorting function (just like Array.prototype.sort) as an argument and sort the DOM elements in-place, and would handle situations where the elements didn’t all have the same parent.

To be honest, I didn’t search for very long — I prefer making this kind of stuff myself anyway — so, I present what I think is one of the simplest ways possible to implement a reliable element-sorting function.

UPDATE: Name changed from sort to sortElements as per David’s comment.

 * jQuery.fn.sortElements
 * --------------
 * @param Function comparator:
 *   Exactly the same behaviour as [1,2,3].sort(comparator)
 * @param Function getSortable
 *   A function that should return the element that is
 *   to be sorted. The comparator will run on the
 *   current collection, but you may want the actual
 *   resulting sort to occur on a parent or another
 *   associated element.
 *   E.g. $('td').sortElements(comparator, function(){
 *      return this.parentNode; 
 *   })
 *   The <td>'s parent (<tr>) will be sorted instead
 *   of the <td> itself.
jQuery.fn.sortElements = (function(){
    var sort = [].sort;
    return function(comparator, getSortable) {
        getSortable = getSortable || function(){return this;};
        var placements ={
            var sortElement =,
                parentNode = sortElement.parentNode,
                // Since the element itself will change position, we have
                // to have some way of storing its original position in
                // the DOM. The easiest way is to have a 'flag' node:
                nextSibling = parentNode.insertBefore(
            return function() {
                if (parentNode === this) {
                    throw new Error(
                        "You can't sort elements if any one is a descendant of another."
                // Insert before flag:
                parentNode.insertBefore(this, nextSibling);
                // Remove flag:
        return, comparator).each(function(i){


  • It’s low-level — you have control over how it sorts (see the “comparator” argument).
  • It lets you sort any arbitrary DOM nodes, as long as none of those nodes are within another one of the nodes to be sorted.
  • It lets you specify what elements will actually be moved (see the “getSortable” argument).


Assuming the following markup:


You could sort the items alphabetically like so:

$('li').sortElements(function(a, b){
    return $(a).text() > $(b).text() ? 1 : -1;

That would result in:


See a rather basic demo here.

jQuery.fn.sortElements on Github

Thanks for reading! Please share your thoughts with me on Twitter. Have a great day!