Skip to content
Related Articles

Related Articles

How to sort an HTML list using JavaScript ?

Improve Article
Save Article
  • Difficulty Level : Medium
  • Last Updated : 08 Jan, 2021
Improve Article
Save Article

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.

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


node.insertBefore( newnode, existingnode )

Parameters: This method accept two parameters as mentioned above and described below:

  • newnode: It is the required parameter. This parameter contains the new node object which needs to insert.
  • existingnode: It is the required parameter. It describes the position where new node insert before this node. If it set to null then insertBefore method will insert the new node at the end.

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 insertBefore() method in a sorted manner.


<!DOCTYPE html>
        Sort a list alphabetically Using JavaScript
        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;
                /* If the current item is smaller than 
                   the next item then adding it after 
                   it using insertBefore() method */
                if (stop) {
                            li[i + 1], li[i]);
                    run = true;
    <h1 style="text-align:center;
        color: forestgreen;">
    <p style="text-align:center; font-size: 15px;
        font-weight: bold;">
        Click on the button to sort the list
    <ul style="color: crimson;" id="GeekList">
        <button style="color: crimson;"
            Click Here To Sort


  • Before clicking on the button:
  • After clicking on the button:

My Personal Notes arrow_drop_up
Related Articles

Start Your Coding Journey Now!