Open In App

How to sort an HTML list using JavaScript ?

Last Updated : 12 Jan, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

In this article, we are given a list of elements and the task is to sort them alphabetically and put each element in the list with the help of JavaScript. We have a method to sort an HTML list using JavaScript that are described below:

insertBefore() method: The insertBefore() method in HTML DOM is used to insert a new node before the existing node as specified by the user.

Syntax:

node.insertBefore( newnode, existingnode )

Example: In this example, the list elements are selected and then passed to a function for sorting. After sorting they are appended to the Parent element using the insertBefore() method in a sorted manner.

HTML




<body>
    <h1 style="text-align:center;
        color: forestgreen;">
        GeeksForGeeks
    </h1>
    <p style="text-align:center; font-size: 15px;
        font-weight: bold;">
        Click on the button to sort the list
    </p>
  
    <ul style="color: crimson;" id="GeekList">
        <li>Geeks</li>
        <li>For</li>
        <li>GFG</li>
        <li>GeeksForGeeks</li>
    </ul>
    <br>
  
    <center>
        <button style="color: crimson;" onclick="sort()">
            Click Here To Sort
        </button>
    </center>
    <script>
        function sort() {
          
            // Declaring Variables
            var geek_list, i, run, li, stop;
          
            // Taking content of list as input
            geek_list = document.getElementById("GeekList");
          
            run = true;
          
            while (run) {
                run = false;
                li = geek_list.getElementsByTagName("LI");
          
                // Loop traversing through all the list items
                for (i = 0; i < (li.length - 1); i++) {
                    stop = false;
                    if (li[i].innerHTML.toLowerCase() > 
                        li[i + 1].innerHTML.toLowerCase()) {
                        stop = true;
                        break;
                    }
                }
          
                /* If the current item is smaller than 
                   the next item then adding it after 
                   it using insertBefore() method */
                if (stop) {
                    li[i].parentNode.insertBefore(
                            li[i + 1], li[i]);
          
                    run = true;
                }
            }
        }
    </script>
</body>


Output:

Sort an HTML list

Sort an HTML list



Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads