Menu Close

How To Sort a Html List Using Jquery

Sort list jquery

Let’s see how to sort a html list alphabetically by using jQuery. We are using the jQuery text() method to sort the html list. This method is used to set/return the text content of all matched elements. After the elements are sorted and they are appended to the parent element by using appendTo() method in sorted manner. Follow the below example to achieve this.


Create a html file on your computer and add the below snippet to this file.

<!DOCTYPE html>
    <title>How To Sort a Html List Using Jquery</title>
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link rel="stylesheet" href="style.css">
    <link href="" rel="stylesheet">
    <script src=""></script>
    <script src=""></script>
<div class="container sort-elements">
    <h3>click the below button to sort the list</h3><br>
    <button>click here</button><br><br>
    <p id = "sort_down"></p><br>
        function Ascending_sort(a, b) {
            return ($(b).text().toUpperCase()) < 
                ($(a).text().toUpperCase()) ? 1 : -1; 
            $('button').on('click', function() {
                $("ul li").sort(Ascending_sort).appendTo('ul');

Create an external stylesheet, add the below css to this file and link in to your html file.

body {
    font-family: Arial, sans-serif;
    padding: 50px;
    background: #fafafa;
.sort-elements h3{ 
    font-size: 15px; 
    font-weight: bold;
Posted in HTML, jQuery

You can also read...