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