Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
-3
rated 0 times [  0] [ 3]  / answers: 1 / hits: 34602  / 14 Years ago, mon, february 21, 2011, 12:00:00

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>

More From » javascript

 Answers
13

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;
});

[#93646] Friday, February 18, 2011, 14 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
margaritakristinak

Total Points: 502
Total Questions: 127
Total Answers: 98

Location: England
Member since Mon, May 17, 2021
3 Years ago
;