Search code examples
javascripthtmlroman-numerals

Sorting html elements that were ordered by roman numeral IDs


I have generated HTML (i have no control of this) similar to this:

<ul id="list">
  <li id="I">one</li>
  <li id="II">two</li>
  <li id="III">three</li>
  <li id="IV">four</li>
  <li id="IX">nine</li>
  <li id="V">five</li>
  <li id="VI">six</li>
  <li id="VII">seven</li>
   .....
   ......
   ......
</ul> 

Basically, the code (SQL -> XML -> XSLT) that generated this is sorting by a field (which represents a roman numeral field) alphabetically. Is there a way i can use javascript to reorder the list items from the clientside?


Solution

  • <!doctype html>
    <html lang="en">
    <head>
    <meta charset= "utf-8">
    <title>Small Page</title>
    <script>
    function sortRomanIds(){
        fromRoman= function(s){
            s= s.toUpperCase();
            var L= s.length, sum= 0, i= 0, L= s.length, next, val,
            R={
                M: 1000, D: 500, C: 100, L: 50, X: 10, V: 5, I: 1
            };
            while(i< L){
                val= s.charAt(i++);
                if(!R[val]) return NaN;
                val= R[val];
                next= R[(s.charAt(i) || 'N')] || 0;
                if(next> val) val*= -1;
                sum+= val;
            }
            return sum
        }
        var U= document.getElementById('list'), Li= U.childNodes, 
        L= Li.length, A= [];
        for(var i= 0; i<L; i++){
            if(Li[i].id) A.push(Li[i]);
        }
        A.sort(function(a, b){
            return fromRoman(a.id)- fromRoman(b.id)
        });
        while(A.length) U.appendChild(A.shift());
        return U;
    }
    window.onload=function(){
    document.getElementById('list').onclick=sortRomanIds;
    }
    </script>
    </head>
    <body>
    <h1> Small Page</h1>
    <ul id="list">
      <li id="I">one</li>
      <li id="II">two</li>
      <li id="III">three</li>
      <li id="IV">four</li>
      <li id="IX">nine</li>
      <li id="V">five</li>
      <li id="VI">six</li>
      <li id="VII">seven</li>
    </ul> 
    </body>
    </html>