jQuery sort elements using data id

You can use dataset property which stores all of the custom data-* attributes of an element, it returns a string, in case that you want to convert the string to a number you can use parseInt or + operator.

$('.clist div').sort(function(a,b) {
     return a.dataset.sid > b.dataset.sid;
}).appendTo('.clist');

http://jsfiddle.net/CFYnE/

And your own code also work: http://jsfiddle.net/f5mC9/

Edit: Please note that IE10! and below do not support the .dataset property, if you want to support all browsers you can use jQuery’s .data() method instead:

$('.clist div').sort(function(a,b) {
     return $(a).data('sid') > $(b).data('sid');
}).appendTo('.clist');

Leave a Comment