Tuesday, December 14, 2010

Sort UL element by the customized sorting funtion by JQuery

We can customize javascript sort() function for any requirement as given below. In this example
it sorts the List items according to text of the fist child.

function SortList() {

var listToSort = $('#tabmenu');
var listitems = listToSort.children('li').get();
listitems.sort(function (a, b) {
var contentA = $(a).first().text().toUpperCase();
var contentB = $(b).first().text().toUpperCase();
return (contentA != contentB) ? 1 : 0;
$.each(listitems, function (idx, itm) { listToSort.append(itm); });

You can customize this functionality as you want by changing these two lines of code

var contentA = $(a).first().text().toUpperCase();
var contentB = $(b).first().text().toUpperCase();
As an example,
If you want to sort list items according to the id of the first element you can change like this

var contentA = $(a).first().attr('id').toUpperCase();
var contentB = $(b).first().attr('id').toUpperCase();

No comments:

Post a Comment