Sort divs in jQuery based on attribute 'data-sort'?
Solution 1:
Use this function
var result = $('div').sort(function (a, b) {
var contentA =parseInt( $(a).data('sort'));
var contentB =parseInt( $(b).data('sort'));
return (contentA < contentB) ? -1 : (contentA > contentB) ? 1 : 0;
});
$('#mylist').html(result);
You can call this function just after adding new divs.
If you want to preserve javascript events within the divs, DO NOT USE html replace as in the above example. Instead use:
$(targetSelector).sort(function (a, b) {
// ...
}).appendTo($container);
Solution 2:
I made this into a jQuery function:
jQuery.fn.sortDivs = function sortDivs() {
$("> div", this[0]).sort(dec_sort).appendTo(this[0]);
function dec_sort(a, b){ return ($(b).data("sort")) < ($(a).data("sort")) ? 1 : -1; }
}
So you have a big div like "#boo" and all your little divs inside of there:
$("#boo").sortDivs();
You need the "? 1 : -1" because of a bug in Chrome, without this it won't sort more than 10 divs! http://blog.rodneyrehm.de/archives/14-Sorting-Were-Doing-It-Wrong.html
Solution 3:
Answered the same question here:
- https://stackoverflow.com/a/23298715/1007358
To repost:
After searching through many solutions I decided to blog about how to sort in jquery. In summary, steps to sort jquery "array-like" objects by data attribute...
- select all object via jquery selector
- convert to actual array (not array-like jquery object)
- sort the array of objects
- convert back to jquery object with the array of dom objects
Html
<div class="item" data-order="2">2</div> <div class="item" data-order="1">1</div> <div class="item" data-order="4">4</div> <div class="item" data-order="3">3</div>
Plain jquery selector
$('.item');
[<div class="item" data-order="2">2</div>, <div class="item" data-order="1">1</div>, <div class="item" data-order="4">4</div>, <div class="item" data-order="3">3</div> ]
Lets sort this by data-order
function getSorted(selector, attrName) { return $($(selector).toArray().sort(function(a, b){ var aVal = parseInt(a.getAttribute(attrName)), bVal = parseInt(b.getAttribute(attrName)); return aVal - bVal; })); }
> getSorted('.item', 'data-order')
[<div class="item" data-order="1">1</div>, <div class="item" data-order="2">2</div>, <div class="item" data-order="3">3</div>, <div class="item" data-order="4">4</div> ]
See how getSorted() works.
Hope this helps!