Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>For a solution that works for any arbitrary number of child divs with numbers in any range, you can use a function like this (that actually parses the number of our the ID and does a true numeric sort on it):</p> <pre><code>function sortChildrenDivsById(parentId) { var parent = document.getElementById(parentId); // get child divs var children = parent.getElementsByTagName("div"); var ids = [], obj, i, len; // build an array of objects that has both the element // and a parsed div number in it so we can sort for (i = 0, len = children.length; i &lt; len; i++) { obj = {}; obj.element = children[i]; obj.idNum = parseInt(children[i].id.replace(/[^\d]/g, ""), 10); ids.push(obj); } // sort the array ids.sort(function(a, b) {return(a.idNum - b.idNum);}); // append in sorted order for (i = 0; i &lt; ids.length; i++) { parent.appendChild(ids[i].element); } } </code></pre> <p>Working example here: <a href="http://jsfiddle.net/jfriend00/v9mCM/" rel="nofollow">http://jsfiddle.net/jfriend00/v9mCM/</a></p> <p>FYI, this is cross-browser, plain javascript and will even work in old browsers without shims.</p> <hr> <p>Here's another way of doing it with slightly less code: </p> <pre><code>function sortChildrenDivsById(parentId) { var parent = document.getElementById(parentId); var children = parent.getElementsByTagName("div"); var ids = [], i, len; for (i = 0, len = children.length; i &lt; len; i++) { ids.push(parseInt(children[i].id.replace(/^.*_/g, ""), 10)); } ids.sort(function(a, b) {return(a - b);}); for (i = 0, len = ids.length; i &lt; len; i++) { parent.appendChild(document.getElementById("dv_" + ids[i])); } } </code></pre> <p>Working example: <a href="http://jsfiddle.net/jfriend00/TqJVb/" rel="nofollow">http://jsfiddle.net/jfriend00/TqJVb/</a></p> <p>All the ids nums are parsed out and put into an array which is sorted and then each object is looked up by id and reinserted in sorted order. This wouldn't be quite as fast as the first one, but it's less code.</p>
 

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