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.

Example

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

<!DOCTYPE html>
<html> 
<head>
    <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="https://cdn.jsdelivr.net/npm/bootstrap@5.2.3/dist/css/bootstrap.min.css" rel="stylesheet">
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.2.3/dist/js/bootstrap.bundle.min.js"></script>
    
</head>
<body>
<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>
    <ul>
        <li>Red</li>
        <li>Green</li>
        <li>Yellow</li>
        <li>Orange</li>
        <li>Violet</li>
        <li>Blue</li>
    </ul><br>           
</div> 
</body>  
    <script>         
        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');
                $("#sort_down").text("sorted");
            }); 
    </script>
</html>
 

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

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

You can also read...