16-04-2010

Javascript Sorting an unordered list

Use this function to sort elements inside an unordered html list <ul>

source: http://www.go4expert.com/forums/showthread.php?t=1947

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();
      });
 
  }

Alternative sorting function for unordered list elements:

source : http://stackoverflow.com/questions/1134976/jquery-sort-list-items-alphabetically

function sortUnorderedList(ul, sortDescending) {
  if(typeof ul == "string")
    ul = document.getElementById(ul);
 
  // Idiot-proof, remove if you want
  if(!ul) {
    alert("The UL object is null!");
    return;
  }
 
  // Get the list items and setup an array for sorting
  var lis = ul.getElementsByTagName("LI");
  var vals = [];
 
  // Populate the array
  for(var i = 0, l = lis.length; i < l; i++)
    vals.push(lis[i].innerHTML.toUpperCase());
 
  // Sort it
  vals.sort();
 
  // Sometimes you gotta DESC
  if(sortDescending)
    vals.reverse();
 
  // Change the list on the page
  for(var i = 0, l = lis.length; i < l; i++)
    lis[i].innerHTML = vals[i];
}

Comments:

Your comment:

»

 

[x]