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.

+2


source to share


4 answers


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");

      

+2


source


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.

+1


source


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);

      

+1


source


Surely all of your hrefs here start with http: // or www? How will sorting help?

Would an ordered list not do the job?

0


source







All Articles