Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to sort DOM elements while selecting in jQuery?

Tags:

jquery

sorting

I have the following DIVs on my page:

<div id="pi_div3">
  Div 3
</div>
<div id="pi_div2">
  Div 2
</div>
<div id="pi_div1">
  Div 1
</div>
<div id="pi_div6">
  Div 6
</div>
<div id="pi_div5">
  Div 5
</div>
<div id="pi_div4">
  Div 4
</div>

I am trying to select the Divs using the jQuery code $("div[id*=pi_div]").

I need the divs to be sorted based on their IDs when I do an each() on the selector. When I loop through the DIVs, the order should be: PI_DIV1, PI_DIV2, PI_DIV3, PI_DIV4, PI_DIV5, PI_DIV6. How can I do that in jQuery?

like image 468
PushCode Avatar asked Feb 14 '13 15:02

PushCode


2 Answers

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.

like image 121
koopajah Avatar answered Nov 16 '22 18:11

koopajah


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/

like image 8
Tomalak Avatar answered Nov 16 '22 19:11

Tomalak