Tuesday, June 9, 2026
HomeLanguagesJavascriptHow to sort an HTML list using JavaScript ?

How to sort an HTML list using JavaScript ?

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

RELATED ARTICLES

Most Popular

Dominic
32515 POSTS0 COMMENTS
Milvus
131 POSTS0 COMMENTS
Nango Kala
6895 POSTS0 COMMENTS
Nicole Veronica
12012 POSTS0 COMMENTS
Nokonwaba Nkukhwana
12109 POSTS0 COMMENTS
Shaida Kate Naidoo
7018 POSTS0 COMMENTS
Ted Musemwa
7262 POSTS0 COMMENTS
Thapelo Manthata
6976 POSTS0 COMMENTS
Umr Jansen
6963 POSTS0 COMMENTS