Join the social network of Tech Nerds, increase skill rank, get work, manage projects...
 
  • How to sort a list items alphabetically using JavaScript

    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 8.12k
    Comment on it

    Hello All,

    Working with HTML and JavaScript, many time we render html in our page with the help of JavaScript, like adding a list that has many list items.

    To show that list in a alphabetical order (ascending or descending order) in our HTML page using JavaScript we can use following block of code:

    function SortList(elementId) {
        var mylist = $("#" + elementId);
        $(mylist).children("li").sort(function (item1, item2) {
            var compFirst = $(item1).text().toUpperCase();
            var compSecond = $(item2).text().toUpperCase();
            if (!((compFirst != "") || (compSecond == "DEFAULT"))) {
                return (compFirst < compSecond) ? -1 : (compFirst > compSecond) ? 1 : 0;
            }
        }).appendTo(mylist);
    }
    

    In this above function, we are passing the id of the HTML List and by using the sort function of JQuery, we are sorting the elements by comparing each item with other and appending it to list in sorted order.

 0 Comment(s)

Sign In
                           OR                           
                           OR                           
Register

Sign up using

                           OR                           
Forgot Password
Fill out the form below and instructions to reset your password will be emailed to you:
Reset Password
Fill out the form below and reset your password: