0

Possible Duplicate:
How to sort LI's based on their ID

I have a div that is dynamically populated with various images and looks something like:

<div id="images">
<img id="img1" src="..." />
<img id="img3" src="..." />
<img id="img2" src="..." />
<img id="img6" src="..." />
<img id="img5" src="..." />
<img id="img4" src="..." />
</div>

Using javascript and jQuery, i need to sort the images into order of ID but i'm struggling. Heres what I've got so far:

var toSort = $('#images').children;
toSort = Array.prototype.slice.call(toSort,0);


toSort.sort(function(a,b){
   var aord = +a.id.substr(6);
   var bord = +b.id.substr(6);  
   return aord - bord; 
});


var parent = $('#images');
parent.innerHTML="";
for(var i=0, l = toSort.length; i<l; ++i){
   parent.appendChild(toSort[i]);
}

How close am I? What am I doing wrong? Thanks guys.

Community
  • 1
  • 1
user1055650
  • 417
  • 2
  • 8
  • 13

3 Answers3

3
var imgs = $('#images img');
imgs.sort(function(a, b) {
   return a.id > b.id;
});
$('#images').html(imgs);
​

DEMO

OR

var imgs = $('#images img');
imgs.sort(function(a, b) {
   return +a.id.replace('img','') -  +b.id.replace('img','');
});
$('#images').html(imgs);

DEMO

Edition with your code:

var parent = $('#images'),
    children = parent.children(),
    toSort = Array.prototype.slice.call(children, 0);

parent[0].innerHTML = ""; //or parent.empty();

toSort.sort(function(a, b) {
    var aord = +a.id.substr(3);
    var bord = +b.id.substr(3);
    return aord - bord;
});

for (var i = 0; i < toSort.length; i++) {
    parent.append(toSort[i]);
}

DEMO

thecodeparadox
  • 86,271
  • 21
  • 138
  • 164
0
var elem = $('#images'),
    imgs = elem.find('img');
imgs.sort(function(a, b) {
   return a.id.toUpperCase().localeCompare(b.id.toUpperCase());
});
$.each(imgs, function(idx, itm) { elem.append(itm); });

FIDDLE

adeneo
  • 312,895
  • 29
  • 395
  • 388
0

I think @thecodeparadox version is better but here is your code corrected a little bit. I changed img to span to make it more visible.

http://jsfiddle.net/whnyn/