title: Javascript only - sort a bunch of DIVs
body: <blockquote>
    <p><strong>Possible Duplicate:</strong><br>
    <a href="https://stackoverflow.com/questions/282670/easiest-way-to-sort-dom-nodes">Easiest way to sort DOM nodes?</a>  </p>
  </blockquote>
  
  
  
  <p>I have a list of DIVs, like this :</p>
  
  <pre><code>&lt;div id="list"&gt;
      &lt;div id="categorie5.1-4"&gt;4&lt;/div&gt;
      &lt;div id="categorie5.1-3"&gt;3&lt;/div&gt;
      &lt;div id="categorie5.1-5"&gt;5&lt;/div&gt;
      &lt;div id="categorie5.1-1"&gt;1&lt;/div&gt;
      &lt;div id="categorie5.1-2"&gt;2&lt;/div&gt;
  &lt;/div&gt;
  </code></pre>
  
  <p>and I want to sort them, using Javascript only (no Jquery) to have a result like this :</p>
  
  <pre><code>1
  2
  3
  4
  5
  </code></pre>
  
  <p>If needed, I can use the end of the DIV ids : "categorie5.1-<strong>4</strong>" (server-side I can define the DIV ids to embedded the wanted order)</p>
  
  <p>Thank you very much for your help!</p>
  
  <hr>
  
  <p>Here is the complete code :</p>
  
  <pre><code>&lt;html&gt;
  &lt;head&gt;
  &lt;script type="text/javascript"&gt;
  function sortdiv() {
  var container = document.getElementById("list");
  var elements = container.childNodes;
  var sortMe = [];
  for (var i=0; i&lt;elements.length; i++) {
      if (!elements[i].id) {
          continue;
      }
      var sortPart = elements[i].id.split("-");
      if (sortPart.length &gt; 1) {
          sortMe.push([ 1 * sortPart[1] , elements[i] ]);
      }
  }
  sortMe.sort(function(x, y) {
      return x[0] - y[0];
  });
  for (var i=0; i&lt;sortMe.length; i++) {
      container.appendChild(sortMe[i][1]);
  }
  document.getElementById("button").innerHTML = "done.";
  }
  &lt;/script&gt;
  &lt;/head&gt;
  &lt;body&gt;
  &lt;div id="list"&gt;
      &lt;div id="categorie5.1-4"&gt;4&lt;/div&gt;
      &lt;div id="categorie5.1-3"&gt;3&lt;/div&gt;
      &lt;div id="categorie5.1-5"&gt;5&lt;/div&gt;
      &lt;div id="categorie5.1-1"&gt;1&lt;/div&gt;
      &lt;div id="categorie5.1-2"&gt;2&lt;/div&gt;
  &lt;/div&gt;
  &lt;div id="button"&gt;&lt;a href="#" onclick="sortdiv();"&gt;sort!&lt;/a&gt;&lt;/div&gt;
  &lt;/body&gt;
  &lt;/html&gt;
  </code></pre>