html - How to sort a complex list in Javascript? -
i'm stuck question while. have nested list, structure looks
volume1 chapter4 chapter3 section3-6 section3-1 volume2... ...
what want create sort function sort volume, chapter, , section.
so, result may
volume1 chapter1 section1-1 ....
so got complex html, here whole html. i'm not sure how swap complex div
i've tried element , put them array.
var tosort = document.getelementbyid('volume5015').children; tosort = array.prototype.slice.call(tosort, 0);
i made fiddle you.
in code trimming whitespaces of text don't compared don't have if don't want.
var $items = $("#to-sort").children(); var $resultlist = $("#list2"); sortmarkup($items, $resultlist); function sortmarkup($elements, $output) { $elements.sort(function(a, b) { var contenta = getpuretext(a).trim(); var contentb = getpuretext(b).trim(); var okay = contenta.touppercase().localecompare(contentb.touppercase()); if( $(a).children().length > 0 ) sortmarkup( $(a).children(), $(a) ); if( $(b).children().length > 0 ) sortmarkup( $(b).children(), $(b) ); console.log("sorting ["+contenta+"] , ["+contentb+"] returned "+okay); return okay; }); $output.append($elements); } function getpuretext(elem) { return $(elem).contents().filter(function() { return this.nodetype == 3; })[0].nodevalue; }
also, using output list, thing not required. feel free modify needs!
Comments
Post a Comment