Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the easiest way to order a <UL>/<OL> in jQuery?

Tags:

jquery

sorting

I'm looking for some sample code that will sort the list items in an HTML list by alphabetical order. Can anyone help?

Here is a sample list for people to work with:

<ul class="alphaList">     <li>apples</li>     <li>cats</li>     <li>bears</li> </ul> 
like image 971
Eric Schoonover Avatar asked Nov 20 '08 05:11

Eric Schoonover


People also ask

How do I sort a list alphabetically in jQuery?

Put the list in an array, use JavaScript's . sort() , which is by default alphabetical, then convert the array back to a list.

How can get ul id in jQuery?

You can use $('li'). parent(). attr('id') to get the id of the parent element.

How do I add an item to a list in UL?

Answer: Use the jQuery append() Method You can simply use the jQuery append() method to add <li> elements in an existing <ul> element.


1 Answers

var items = $('.alphaList > li').get(); items.sort(function(a,b){   var keyA = $(a).text();   var keyB = $(b).text();    if (keyA < keyB) return -1;   if (keyA > keyB) return 1;   return 0; }); var ul = $('.alphaList'); $.each(items, function(i, li){   ul.append(li); /* This removes li from the old spot and moves it */ }); 
like image 152
Chatu Avatar answered Sep 22 '22 18:09

Chatu