1

Sort dynamically created div based on their id.

I have the html structure like below:

<div id="res">
  <div id="3">text 3</div>
  <div id="4">text 4</div>
  <div id="1">text 1</div>
  <div id="2">text 2</div>
</div>

These html are created dynamically.

$("#res").append("<div id="+i+">text "+i+"</div>");

The order may vary(it is created using ajax in for loop). Unluckly divs are displayed in random order.(I don't know the reason).

However after appending the divs to the res div, I decided to sort the divs in correct order based on their id.

So the expected result should be:

<div id="res">
  <div id="1">text 1</div>
  <div id="2">text 2</div>
  <div id="3">text 3</div>
  <div id="4">text 4</div>
</div>

How can I do this?

I tried

$("#resdiv").tsort("",{attr:"id"});

and

$('#res> div').toArray().sort( function(a,b) { a.id - b.id } );

But nothing worked...

Someone can help me..

4
  • $('#res div').sort(function(x, y){return $(x).attr('id')-$(y).attr('id')}); Commented Feb 4, 2016 at 10:23
  • I don't know the reason.......this one you have to debug. .append() works as it should. Commented Feb 4, 2016 at 10:24
  • Why you don't want to do this with javascript? sort() method is available in javascript not in jQuery. Commented Feb 4, 2016 at 10:26
  • $('#res').html( $('#res > div').sort(function(x,y){return parseInt(x.id) > parseInt(y.id) ? 1 : -1}) ); Commented Feb 4, 2016 at 10:47

2 Answers 2

1

Try following

$("#res div").sort(function (elem1, elem2) {
    return parseInt(elem1.id) > parseInt(elem2.id);
}).each(function () {
    var element = $(this);
    element.remove();
    $(element).appendTo("#res");
});

Explanation - You have first sorted the elements on based of id and then iterate over those elements so as to first remove them from html (irrespective of the position) and then appending it back to the container element (this time sorted)

Sign up to request clarification or add additional context in comments.

2 Comments

thanks nikhil..its really helped me..
@next2u - Feel good to help you
0

You can use native JavaScript sort()

var $res = $('#res');
$('div', $res).sort(function(a, b) {
  return parseInt(a.id, 10) - parseInt(b.id, 10);
}).appendTo($res);
// For updating the order you need to append it, which updates elements order
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div id="res">
  <div id="3">text 3</div>
  <div id="4">text 4</div>
  <div id="1">text 1</div>
  <div id="2">text 2</div>
</div>

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.