JSFiddle - React, Tailwind, and code Playground
HTML
<div id="list">
<!-- comment -->
<div id="categorie5.1-4">4</div>
Note that this text does not get sorted
<div id="categorie5.1-3">3</div>
<div id="mwuahaha">Nor does this one, it does not have a valid ID</div>
<div id="categorie5.1-5">5</div>
<div id="categorie5.1-1">1</div>
<div id="categorie5.1-2">2</div>
<div id="categorie5.1-20">20</div>
<div id="categorie5.1-12">12</div>
</div>
JavaScript
function doSort() {
// container is <div id="list">
var container = document.getElementById("list");
// all elements below <div id="list">
var elements = container.childNodes;
// temporary storage for elements which will be sorted
var sortMe = [];
// iterate through all elements in <div id="list">
for (var i=0; i<elements.length; i++) {
// skip nodes without an ID, comment blocks for example
if (!elements[i].id) {
continue;
}
var sortPart = elements[i].id.split("-");
// only add the element for sorting if it has a dash in it
if (sortPart.length > 1) {
/*
* prepare the ID for faster comparison
* array will contain:
* [0] => number which will be used for sorting
* [1] => element
* 1 * something is the fastest way I know to convert a string to a
* number. It should be a number to make it sort in a natural way,
* so that it will be sorted as 1, 2, 10, 20, and not 1, 10, 2, 20
*/
sortMe.push([ 1 * sortPart[1] , elements[i] ]);
}
}
// sort the array sortMe, elements with the lowest ID will be first
sortMe.sort(function(x, y) {
// remember that the first array element is the number, used for comparison
return x[0] - y[0];
});
// finally append the sorted elements again, the old element will be moved to
// the new position
for (var i=0; i<sortMe.length; i++) {
// remember that the second array element contains the element itself
container.appendChild(sortMe[i][1]);
}
}
// ignore this, it adds the button for testing purposes
var btnSort = document.createElement("button");
btnSort.onclick = doSort;
btnSort.innerHTML = "Sort Me!";
document.body.appendChild(btnSort);