Sort an html list with javascript
Solution 1:
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>
Solution 2:
You can try this
var ul = $(".list:first");
var arr = $.makeArray(ul.children("li"));
arr.sort(function(a, b) {
var textA = +$(a).text();
var textB = +$(b).text();
if (textA < textB) return -1;
if (textA > textB) return 1;
return 0;
});
ul.empty();
$.each(arr, function() {
ul.append(this);
});
Live example : http://jsfiddle.net/B7hdx/1
Solution 3:
you can use this lightweight jquery plugin List.js cause
- it's lightweight [only 3K script]
- easy to implement in your existing HTML table using class
- searchable, sortable and filterable
HTML
<div id="my-list">
<ul class="list">
<li>
<h3 class="name">Luke</h3>
</li>
<li>
<h3 class="name">John</h3>
</li>
</ul>
</div>
Javascript
var options = {
valueNames: ['name']
};
var myList = new List('my-list', options);