handlebars.js - Sort Div Elements that are stored in a variable using jQuery -


i have html dom element stored in variable. html generated handlebar.js & json data using jquery. need sort according values csv

var html = "<div id = 'qual'>qual</div> <div id = 'exp'>exp</div> <div id = 'excludefromsorting'></div> <div id = 'edu'>edu</div> <div class='clear'></div> <div id = 'int'>int</div> <div id = 'ref'>ref</div> <div id = 'img'>img</div> <div id = 'obj'>obj</div>"; 

the html complex, more 200 lines of code. html have lot of div tags or without id's, nested div's etc. using simple notation here.

i have sortorder in varibale csv

var sortorder = "obj,exp,qual,edu,int,ref,img"; 

but div tag's above id's definetly exist in generated html (var html definetly have divs corresponding id's.) keep simple var html might have more 100 div's these 7 div's

<div id = "qual">qual</div> <div id = "exp">exp</div> <div id = "edu">edu</div> <div id = "int">int</div> <div id = "ref">ref</div> <div id = "img">img</div> <div id = "obj">obj/div> 

according var sortorder definetly exist in var html in shuffled order.

what need same var html div's sorted according values passed. other div's in var html should not affected.

i guess brief enough explain requirement, posted quesiton

how sort div elements according id csv list using jquery?

but method not working time.

here working example using swapwith function paolo bergantino posted here.

// swapwith // @paolo bergantino // https://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);     }); };  // return jquery object  function sortdivsbyids($html, ids, current) {      current = current || 0;     // mark items needs sorted     if (current ==0) {                $(ids).each(function(i,elem) {$("#" + elem, $html).addclass('sorter');});     }    // reorder / iterates     $('#' + ids[current], $html ).swapwith( $('.sorter', $html).eq(current) );        if (current+1<ids.length) {         return sortdivsbyids($html, ids, current+1)     } else {         //remove marker         $('.sorter', $html).removeclass('sorter')         return $html;           }; } 

usage

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";  var $htmlsorted = sortdivsbyids( $('<div></div>', {html:html}), sortorder.split(',')); alert($htmlsorted.html()); 

fiddle : http://jsfiddle.net/yiernehr/gtehj/1/


Comments