How to sort DOM elements while selecting in jQuery?
Solution 1:
You can call .sort() before calling .each()
$("div[id*=pi_div]").sort(function(a,b){
if(a.id < b.id) {
return -1;
} else {
return 1;
}
}).each(function() { console.log($(this).attr("id"));});
EDIT: I was wondering why the other answers are removing the pi_div
part of the id and I get it. If you compare based on the "strings" pi_div10
will come before pi_div2
.
Solution 2:
If you also want to sort them visibly on the page
$('div[id^="pi_div"]').sort(function (a, b) {
var re = /[^\d]/g;
return ~~a.id.replace(re, '') > ~~b.id.replace(re, '');
})
.appendTo("#container");
Note the ~~
which converts the values into integers, otherwise they would be compared as strings.
See http://jsfiddle.net/Xjc2T/