Sort an html list with javascript

This will probably be the fastest way to do it, since it doesn’t use jQuery:

function sortList(ul){
    var new_ul = ul.cloneNode(false);

    // Add all lis to an array
    var lis = [];
    for(var i = ul.childNodes.length; i--;){
        if(ul.childNodes[i].nodeName === 'LI')
            lis.push(ul.childNodes[i]);
    }

    // Sort the lis in descending order
    lis.sort(function(a, b){
       return parseInt(b.childNodes[0].data , 10) - 
              parseInt(a.childNodes[0].data , 10);
    });

    // Add them into the ul in order
    for(var i = 0; i < lis.length; i++)
        new_ul.appendChild(lis[i]);
    ul.parentNode.replaceChild(new_ul, ul);
}

Call the function like:

sortList(document.getElementsByClassName('list')[0]);

You can sort other lists the same way, and if you have other elements on the same page with the list class you should give your ul an id and pass it in using that instead.

Example JSFiddle

Edit

Since you mentioned that you want it to happen on pageLoad, I’m assuming you want it to happen ASAP after the ul is in the DOM which means you should add the function sortList to the head of your page and use it immediately after your list like this:

<head>
    ...
    <script type="text/javascript">
        function sortList(ul){
            var new_ul = ul.cloneNode(false);
            var lis = [];
            for(var i = ul.childNodes.length; i--;){
                if(ul.childNodes[i].nodeName === 'LI')
                    lis.push(ul.childNodes[i]);
            }
            lis.sort(function(a, b){
               return parseInt(b.childNodes[0].data , 10) - parseInt(a.childNodes[0].data , 10);
            });
            for(var i = 0; i < lis.length; i++)
                new_ul.appendChild(lis[i]);
            ul.parentNode.replaceChild(new_ul, ul);
        }
    </script>
</head>
<body>
    ...
    <ul class="list">
        <li id="alpha">32</li>
        <li id="beta">170</li>
        <li id="delta">28</li>
    </ul>
    <script type="text/javascript">
        !function(){
            var uls = document.getElementsByTagName('ul');
            sortList( uls[uls.length - 1] );
        }();
    </script>
    ...
</body>

Leave a Comment