How to sort DOM elements while selecting in jQuery?

后端 未结 4 1906
伪装坚强ぢ
伪装坚强ぢ 2020-11-28 14:29

I have the following DIVs on my page:

Div 3
Div 2
4条回答
  •  悲哀的现实
    2020-11-28 15:03

    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.

提交回复
热议问题