March 5, 2024 5:01 am

How to Sort List Items using jQuery with anchors

I have found an interesting jQuery code to sort list items on your web pages and writing this tutorial to apply this functionality in your web projects. In this code snippet we create a jQuery function which load all list items of a given id and match text letters and present you in a sorted form, lets see how it works and its demo with source code.

How to Sort List Items using jQuery with anchors

[wpdm_file id=71]DEMO

We use <ul><li>Item</li></ul> lists all the time and implement them in our websites and these lists most of the time unsorted so here is a very simple code snippet to sort these lists with anchors.

HTML List markup



<li><a href="">PHP</a></li>
<li><a href="">jQuery</a></li>
<li><a href="">HTML</a></li>
<li><a href="">CSS</a></li>
<li><a href="">MySQL</a></li>

Above given lists are un-ordered lists with anchor and without anchor and if you have to sort them usually can do it manually.

jQuery code snippet

<script type="text/javascript">
$(function() {
    $.fn.sortList = function() {
    var list = $(this);
    var items = $("li", list).get();
    items.sort(function(a, b) {
        var listItem1 = $(a).text().toUpperCase();
        var listItem2 = $(b).text().toUpperCase();
        return (listItem1 < listItem2) ? -1 : 1;
    $.each(items, function(i, itm) {



Above jQuery code compare each item and change order of each item.

$.fn.sortList = function() create function sortList $(“li”, list).get() get all li items of given id of list, list.append(itm) append items in order $(“ul#sort”).sortList() call function to sort all items of ul with id sort.

[wpdm_file id=71]DEMO

That’s all I hope you like this post please comment your feedback.

Author Huzoor Bux

I am Huzoor Bux from Karachi (Pakistan). I have been working as a PHP Developer from last 5+ years, and its my passion to learn new things and implement them as a practice. Basically I am a PHP developer but now days exploring more in HTML5, CSS and jQuery libraries.

Tutorial Categories:

Leave a Reply

Your email address will not be published. Required fields are marked *