How to sort an unordered list inside an anchor label
I have the following DOM structure (unordered list) that I would like to sort by tag name a href
using jQuery.
The structure looks like this:
<div id="refmenu">
<ul id="list">
<li><a href="....">Google</a></li>
<li><a href="....">Apple</a></li>
<li><a href="....">IBM</a></li>
<li><a href="....">Yahoo!</a></li>
<li><a href="....">Hotmail</a></li>
</ul>
</div>
Based on the above, one would like to be able to run this through a jQuery function that sorts the unordered list names alphabetically, obviously also keeping the link a href
along with the anchor tag names.
Hope someone can help.
Thank.
source to share
Give TinySort a plugin, it will sort the child nodes by content or attributes: Example
Edit -
$("div#refmenu>ul#platsys>li").tsort("a.title");
There is also no reason for additional filtering before the id selector , selecting the tag name does not speed up the performance when selecting by id. Also, your name for your ul is not platsys, so I dont know where you got what ul # list> li should come from , but to cut it all down, some extra unnecessary code I would
$("#refmenu>#list>li").tsort("a.title");
Actually from your html I think it will be the same as:
$("#list>li").tsort("a.title");
source to share
Try the following:
var list = $("#list"),
listItems = Array.prototype.slice.call(list.find("li"));
listItems.sort(function(a, b) {
a = $("a", a).text(), b = $("a", b).text();
return a < b ? -1 : a > b ? 1 : 0;
});
listItems.forEach(function(val) {
list.append($(val).remove());
});
If you want to sort by a different criterion than the anchor text, replace text()
with what you want.
source to share
you can try List.js which will expand the list's capabilities to extreme values ββlike
- it's lightweight [3K script only]
- easy to implement in your existing HTML table using the class
- for searching, sorting and filtering
Html
<div id="my-list">
<ul class="list">
<li>
<h3 class="name">Luke</h3>
</li>
<li>
<h3 class="name">John</h3>
</li>
</ul>
</div>
Javascript
var options = {
valueNames: ['name']
};
var myList = new List('my-list', options);
source to share