Created
April 2, 2011 10:11
-
-
Save joernroeder/899371 to your computer and use it in GitHub Desktop.
jQuery: sort items in a list by text
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* @description | |
* sort items in a list by text | |
* | |
* based on {@link http://stackoverflow.com/questions/1134976/how-may-i-sort-a-list-alphabetically-using-jquery} | |
* | |
* @param {String/Object} Selector or jQuery Object | |
* @param {Boolean} sort descending | |
*/ | |
(function ($) { | |
$.extend({ | |
sortUl: function (ul, sortDescending) { | |
var $ul, | |
$li, | |
texts = [], | |
htmls = {}; | |
if (typeof ul === 'string') { | |
$ul = $(ul); | |
} | |
else if (typeof ul === 'object') { | |
$ul = ul; | |
} | |
// Idiot-proof, remove if you want | |
if (!$ul.length) { | |
$.error("The UL object is null!"); | |
return; | |
} | |
// Get the list items and setup an array for sorting | |
$lis = $ul.children(); | |
// Populate the array | |
$lis.each(function (i, li) { | |
var text = $(li).text(); | |
htmls[text] = $(li).html(); | |
texts.push(text); | |
}); | |
// Sort it | |
texts.sort(); | |
// Sometimes you gotta DESC | |
if (sortDescending) { | |
texts.reverse(); | |
} | |
// Change the list on the page | |
$lis.each(function (i, li) { | |
$(li).html(htmls[texts[i]]); | |
}); | |
} | |
}); | |
}(jQuery)); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment