Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>The reasons why you should use arrays:</p> <ul> <li>NodeLists are read-only (you can't apply array sorting to them)</li> <li>Array operations are super fast compared to DOM operations</li> </ul> <p>So you basically need to convert the options into an array, then apply the <code>sort</code> function to it with the custom compare function. Finally you append back the elements in the correct order.</p> <p><strong>Usage</strong></p> <pre><code>sortSelect("selection_id"); </code></pre> <p><strong>Code [<a href="http://jsbin.com/ayodu3/" rel="nofollow noreferrer">See it in action</a>]</strong></p> <pre><code>(function(window){ // array functions are not working // on nodeLists on IE, we need to // to convert them to array function toArray( obj ) { var i, arr = []; for ( i = obj.length; i--; ){ arr[i] = obj[i]; } return arr; } // custom compare function for sorting // by the option's value function sortByName( a, b ) { if ( a.value &lt; b.value ) return -1; else if( a.value &gt; b.value ) return 1; else return 0; } window.sortSelect = function(id) { // select the elements to be ordered var sel = document.getElementById(id), items = sel.getElementsByTagName("option"), len = items.length; // convert to array, to make sorting possible items = toArray( items ); // do the item sorting by their value items = items.sort( sortByName ); // append them back to the parent in order for ( var i = 0; i &lt; len; i++ ) { sel.appendChild( items[i] ); } }; })(this);​ </code></pre> <p><em>Tested on: IE5.5+, FF2+, Chrome, Opera 9.6+</em></p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload