Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sort by id element using jQuery [duplicate]

I have this code:

<li id="pi_div2"></li>
<li id="pi_div5"></li>
<li id="pi_div4"></li>

I need to sort like this:

<li id="pi_div2"></li>
<li id="pi_div4"></li>
<li id="pi_div5"></li>

My script now:

<script>
    $("li[id*=pi_div]").sort(function(a,b) {
        if(a.id < b.id) {
            return -1;
        }
        else {
            return 1;
        }
    }).each(function() { console.log($(this).attr("id"));});
</script>
like image 613
user3112944 Avatar asked Jan 21 '14 19:01

user3112944


1 Answers

Based upon your original html, you could do something like this:

Html:

<ul id="cat">
    <li id="3">Text 3</li>
    <li id="1">Text 1</li>
    <li id="2">Text 2</li>
</ul>

JavaScript:

$("#cat li").sort(function (a, b) {
    return parseInt(a.id) > parseInt(b.id);
}).each(function () {
    var elem = $(this);
    elem.remove();
    $(elem).appendTo("#cat");
});

Check out this fiddle.


EDIT:

As @KiKo has correctly pointed out, the above code breaks if you have a list longer than ten elements. You can fix this by replacing the "greater than" in the sort function with a minus.

Html:

<ul id="cat">
  <li id="3">Text 3</li>
  <li id="2">Text 2</li>
  <li id="1">Text 1</li>
  <li id="9">Text 9</li>
  <li id="11">Text 11</li>
  <li id="5">Text 5</li>
  <li id="7">Text 7</li>
  <li id="6">Text 6</li>
  <li id="12">Text 12</li>
  <li id="4">Text 4</li>
  <li id="10">Text 10</li>
  <li id="8">Text 8</li>
</ul>

JavaScript:

$("#cat li").sort(function(a, b) {
  return parseInt(a.id) - parseInt(b.id);
}).each(function() {
  var elem = $(this);
  elem.remove();
  $(elem).appendTo("#cat");
});

Here's a new JSFiddle.

like image 114
Jamie Dunstan Avatar answered Oct 11 '22 02:10

Jamie Dunstan