Mircea
Mircea

Reputation: 11593

jQuery arrange li order base on #ID

I have the following code:

<ul>
<li id="project_25">Proj Something</li>
<li id="project_26">Proj Blah</li>
<li id="project_27">Proj Else</li>
<li id="project_31">Proj More</li>
...
</ul>

Is there a way to arrange these LIs, reverse their order, based on the LI ID?

Something like:

<ul>
<li id="project_31">Proj More</li>
<li id="project_27">Proj Else</li>
<li id="project_26">Proj Blah</li>
<li id="project_25">Proj Something</li>
...
</ul>

Thank you.

Upvotes: 3

Views: 3987

Answers (2)

jAndy
jAndy

Reputation: 235962

var arr = $('li').get();    
arr.reverse();

$.each(arr, function(i,v){
    $('ul').append(this);
});

Upvotes: 5

Raja
Raja

Reputation: 3618

Please try the code given below:

var mylist = $('ul');
var listitems = mylist.children('li').get();
listitems.sort(function(a, b) {
   var compA = $(a).text().toUpperCase();
   var compB = $(b).text().toUpperCase();
   return (compA < compB) ? -1 : (compA > compB) ? 1 : 0;
})
$.each(listitems, function(idx, itm) { mylist.append(itm); });

I found this here.

HTH

Upvotes: 2

Related Questions