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>
First you have to get all divs:
var toSort = document.getElementById('list').children;
toSort
will be a NodeList
. You have to transform it to an array:
toSort = Array.prototype.slice.call(toSort, 0);
and then you can pass a callback to the sort
method:
toSort.sort(function(a, b) {
var aord = +a.id.split('-')[1];
var bord = +b.id.split('-')[1];
return aord - bord;
});
Edit: As @Lekensteyn already noted, comparing IDs only works if you have only single digit numbers. Fixed it to support arbitrary numbers.
You have to loop over this array and append the elements again:
var parent = document.getElementById('list');
parent.innerHTML = "";
for(var i = 0, l = toSort.length; i < l; i++) {
parent.appendChild(toSort[i]);
}
Edit: fixed typo
DEMO
Update: If you have so many elements, caching of the IDs could be done like so:
var cache = {
add: function(id) {
var n = +id.split('-')[1];
this[id] = n;
return n;
}
};
toSort.sort(function(a, b) {
var aord = cache[a.id] || cache.add(a.id);
var bord = cache[b.id] || cache.add(b.id);
return aord - bord;
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With