My solution is this:
- stop using classes to store variables; that's what
data-
attributes are for. - loop over the elements to be moved, creating an array of {element,order} pairs
- sort the pairs into proper order
- loop over the pairs doing the insert.
Working demo: http://jsfiddle.net/qM27z/3/
var tomove =
$('[data-order]').map(function() {
return { element: this, order: $(this).data("order") };
}).get().sort(function(a,b) { return a.order-b.order; });
$.each(tomove, function(i, tm) {
$(tm.element).insertBefore('.container .box:nth-child('+tm.order+')')
});