I have a sorting method that I want to sort my divs based on their data-position attribute. At the moment, for some reason the function sorts the divs based only on the first digit, and not the whole number. Here is an example in my html which shows that:
html
<div class="parent" data-position="1">
...
</div>
<div class="parent" data-position="27">
...
</div>
<div class="parent" data-position="3">
...
</div>
Here's the js
$('body').on('click', '.new_comments', function(e) {
var divArr = $(".parent");
divArr.sort(function(a, b) {
return $(a).attr('data-position') > $(b).attr('data-position') ? 1: -1;
});
$(".comments_container").append(divArr);
});
Any idea why it does this and how to fix it?
$(a).attr('data-position')
Attr returns the attribute value as a string, so you're comparison is comparing strings, not numbers, which is what you are expecting I assume. Instead of using attr() use data().
$(a).data('position')
The difference between the two is that jQuery will try to auto convert the value in the attribute to a number if it can when you use data(). So with the values converted to numbers, you should see the sorting you expect.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With