Sorting nodes is not so simple, you may have to deal with other nodes that may interfere. Anyway, here is a function that takes a NodeList or HTMLCollection, converts it into an array, sorts it, then returns the nodes in order. Note that the elements are placed at the bottom of the parent element, so all other elements will be located at the top. In any case, it demonstrates an approach that you can adapt.
There are many other approaches, including others using DOM methods, beware of any based on markup markup. Also, beware of cloning elements, as this may have unwanted side effects for listeners (they may or may not be removed, depending on the browser and how they were added).
<script type="text/javascript"> function getText(el) { return el.textContent || el.innerText || ''; } function sortElements(nodeList) { </script> <div>0</div> <div>4</div> <div>2</div> <div>3</div> <div>5</div> <button onclick="sortElements(document.getElementsByTagName('div'))">Sort</button>
source share