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..
.append()works as it should.sort()method is available in javascript not in jQuery.$('#res').html( $('#res > div').sort(function(x,y){return parseInt(x.id) > parseInt(y.id) ? 1 : -1}) );