Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sort an html list with javascript

Tags:

I have a set of three list items that I would like to automatically display from high to low on page load. Ideally using jquery or javascript.

<ul class="list">
<li id="alpha">32</li>
<li id="beta">170</li>
<li id="delta">28</li>
</ul>

Each list item needs its own ID because they each have individual background images. The numbers must text nodes so that a user can edit them.

like image 601
danssker Avatar asked Jan 12 '12 15:01

danssker


1 Answers

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>
like image 74
Paul Avatar answered Oct 12 '22 02:10

Paul