Guest User

Untitled

a guest
May 26th, 2018
88
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.98 KB | None | 0 0
  1. function sortUnorderedList(ul, sortDescending) {
  2. if(typeof ul == "string")
  3. ul = document.getElementById(ul);
  4.  
  5. // Idiot-proof, remove if you want
  6. if(!ul) {
  7. alert("The UL object is null!");
  8. return;
  9. }
  10.  
  11. // Get the list items and setup an array for sorting
  12. var lis = ul.getElementsByTagName("LI");
  13. var vals = [];
  14.  
  15. // Populate the array
  16. for(var i = 0, l = lis.length; i < l; i++)
  17. vals.push(lis[i].innerHTML);
  18.  
  19. // Sort it
  20. vals.sort();
  21.  
  22. // Sometimes you gotta DESC
  23. if(sortDescending)
  24. vals.reverse();
  25.  
  26. // Change the list on the page
  27. for(var i = 0, l = lis.length; i < l; i++)
  28. lis[i].innerHTML = vals[i];
  29. }
  30.  
  31. sortUnorderedList("ID_OF_LIST");
  32.  
  33. var mylist = $('#myUL');
  34. var listitems = mylist.children('li').get();
  35. listitems.sort(function(a, b) {
  36. var compA = $(a).text().toUpperCase();
  37. var compB = $(b).text().toUpperCase();
  38. return (compA < compB) ? -1 : (compA > compB) ? 1 : 0;
  39. })
  40. $.each(listitems, function(idx, itm) { mylist.append(itm); });
Add Comment
Please, Sign In to add comment