Reputation: 47945
Let me show us my scenario and my problem.
This is a list of div that are ordered by the content of categories1
alphabetically by jQuery when the page is loaded :
<div id="container">
<div class="categories">
<div class="categories1">
Ernest
</div>
</div>
<div class="categories">
<div class="categories1">
Andy
</div>
</div>
<div class="categories">
<div class="categories1">
Mark
</div>
</div>
</div>
// result
Andy
Ernest
Mark
Now, when I try to append an element and then ordering the elements, there is a trouble : in fact the last element inserted is not ordered, but it's just appended at the end of the list :
<div class="categories">
<div class="categories1">
Buddy
</div>
</div>
// result
Andy
Ernest
Mark
Buddy
This is the sorting function :
$(function() {
var items = $('.categories1').get();
items.sort(function(x,y) {
return $(x).text() > $(y).text();
});
$('#container').empty();
$(items).each(function() {
$('#container').append($(this).parent());
});
});
Why this behaviour? And how can I fix it?
Upvotes: 1
Views: 990
Reputation: 228182
Not sure if this is the best fix, but you could $.trim
the text: http://jsfiddle.net/WEtML/4/
items.sort(function(x,y) {
return $.trim($(x).text()) > $.trim($(y).text());
});
Upvotes: 2
Reputation: 1459
You have a whitespace problem. Inspect your markup after inserting. The first items start with a space and Buddy does not.
<div id="container">
<div class="categories">
<div class="categories1"> Andy </div>
</div>
<div class="categories">
<div class="categories1"> Ernest </div>
</div>
<div class="categories">
<div class="categories1"> Mark </div>
</div>
<div class="categories">
<div class="categories1">Buddy</div>
</div>
</div>
Upvotes: 2