Sometimes we need a sorted UL (un-ordered list) in a static page, like a blog, we can use JavaScript to the sort the list.
I faced a similar problem with my blog, so I implement a simple bubble sort on the list, the list will be sorted if the browser supports JavaScript, else it will still display the unsorted list.
The JavaScript
The Whole HTML:
I faced a similar problem with my blog, so I implement a simple bubble sort on the list, the list will be sorted if the browser supports JavaScript, else it will still display the unsorted list.
The JavaScript
Code: JavaScript
function sortList(listId)
{
// Get the ul object
var oUl = document.getElementById(listId);
/* Perform a Bubble Sort on the list items */
for(var i in oUl.childNodes)
{
var x = oUl.childNodes[i];
for(var j in oUl.childNodes)
{
var y = oUl.childNodes[j];
if((x.innerText != 'undefined' || y.innerText != 'undefined') && x.innerText>y.innerText)
{
// Skip if x is already the first list item
if(oUl.firstChild!=x)
oUl.insertBefore(y,x);
}
}
}
}
/* Define innerText for Mozilla based browsers */
if((typeof HTMLElement != 'undefined') && (HTMLElement.prototype.__defineGetter__ != 'undefined'))
{
HTMLElement.prototype.__defineGetter__("innerText", function (){
var r = this.ownerDocument.createRange();
r.selectNodeContents(this);
return r.toString();
});
}
The Whole HTML:
HTML Code:
<HTML> <HEAD> <TITLE> New Document <META NAME="Author" CONTENT="Pradeep"> <script> function sortList(listId) { // Get the ul object var oUl = document.getElementById(listId); /* Perform a Bubble Sort on the list items */ for(var i in oUl.childNodes) { var x = oUl.childNodes[i]; for(var j in oUl.childNodes) { var y = oUl.childNodes[j]; if((x.innerText != 'undefined' || y.innerText != 'undefined') && x.innerText>y.innerText) { // Skip if x is already the first list item if(oUl.firstChild!=x) oUl.insertBefore(y,x); } } } } /* Define innerText for Mozilla based browsers */ if((typeof HTMLElement != 'undefined') && (HTMLElement.prototype.__defineGetter__ != 'undefined')) { HTMLElement.prototype.__defineGetter__("innerText", function (){ var r = this.ownerDocument.createRange(); r.selectNodeContents(this); return r.toString(); }); } window.onload=function() { sortList("names"); } </script> </HEAD> <BODY> <ul id="names"> <li>Pradeep</li> <li>Asha</li> <li>Manindar</li> <li>Tanaz</li> </ul> </BODY> </HTML>

