JSFiddle - React, Tailwind, and code Playground
by yiernehr
HTML
<div id="test"></div>
<p>sort to : obj,exp,qual,edu,int,ref,img</p>
<button>sort</button>
JavaScript
// swapWith
// from @Paolo Bergantino
// http://stackoverflow.com/questions/698301/is-there-a-native-jquery-function-to-switch-elements/698386#698386
jQuery.fn.swapWith = function(to) {
return this.each(function() {
var copy_to = $(to).clone(true);
var copy_from = $(this).clone(true);
$(to).replaceWith(copy_from);
$(this).replaceWith(copy_to);
});
};
function sortDivsByIds($html, ids, current) {
current = current || 0;
// mark items that needs to be sorted
if (current ==0) {
$(ids).each(function(i,elem) {$("#" + elem, $html).addClass('sorter');});
}
// reorder
$('#' + ids[current], $html ).swapWith( $('.sorter', $html).eq(current) );
if (current+1<ids.length) {
return sortDivsByIds($html, ids, current+1)
} else {
$('.sorter', $html).removeClass('sorter')
return $html;
};
}
var html = '<div id = "qual" >Qual</div><div id = "exp" >Exp</div><div id = "edu" >Edu</div><div id = "int" >Int</div><div class="another">dont sort me</div><div id = "ref" >Ref</div><div>dont sort me 2</div><div id = "img" >Img</div><div id = "obj">Obj</div>';
var sortorder = "obj,exp,qual,edu,int,ref,img";
$('button').on('click', function() {
var $htmlsorted = sortDivsByIds( $('<div></div>', {html:html}), sortorder.split(','));
$("#test").html($htmlsorted.html());
});