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>
Put the list in an array, use JavaScript's . sort() , which is by default alphabetical, then convert the array back to a list.
You can use $('li'). parent(). attr('id') to get the id of the parent element.
Answer: Use the jQuery append() Method You can simply use the jQuery append() method to add <li> elements in an existing <ul> element.
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 */ });
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With