Skip to content

Instantly share code, notes, and snippets.

@kiennt2
Last active December 18, 2015 15:19
Show Gist options
  • Select an option

  • Save kiennt2/237fd9caee1a72e1d624 to your computer and use it in GitHub Desktop.

Select an option

Save kiennt2/237fd9caee1a72e1d624 to your computer and use it in GitHub Desktop.
Sorting Elements with jQuery
// sort by class
var mylist = jQuery('ul');
var listitems = mylist.children('li').get();
listitems.sort(function(a, b) {
var compA = jQuery(a).attr("class");
var compB = jQuery(b).attr("class");
return (compA < compB) ? -1 : (compA > compB) ? 1 : 0;
})
jQuery(document).ready(function(){
jQuery.each(listitems, function(idx, itm) { mylist.append(itm); });
});
//sort by content
var mylist = $('ul');
var listitems = mylist.children('li').get();
listitems.sort(function(a, b) {
var compA = $(a).text().toUpperCase();
var compB = $(b).text().toUpperCase();
return (compA < compB) ? -1 : (compA > compB) ? 1 : 0;
})
$.each(listitems, function(idx, itm) { mylist.append(itm); });
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment