list - Sort links with javascript? -
i'd sort list links alphabetical code:
!doctype html> <html> <head> <title>sort list items alphabetically javascript</title> <script type="text/javascript"> function sortunorderedlist(ul, sortdescending) { if(typeof ul == "string") ul = document.getelementbyid(ul); var lis = ul.getelementsbytagname("li"); var vals = []; for(var = 0, l = lis.length; < l; i++) vals.push(lis[i].innerhtml); vals.sort(); if(sortdescending) vals.reverse(); for(var = 0, l = lis.length; < l; i++) lis[i].innerhtml = vals[i]; } window.onload = function() { var desc = false; document.getelementbyid("test").onclick = function() { sortunorderedlist("list", desc); desc = !desc; return false; } } </script> </head> <body> <div id="test"> <a href="#">sort list</a></div> <ul id="list"> <li>peter</li> <li>mary</li> <li>paul</li> <li>allen</li> <li>james</li> <li>vicki</li> <li>brock</li> <li>dana</li> <li>frank</li> <li>gil</li> <li>helen</li> </ul> </body>
but when want add links names, list gets messed (not alphabetical anymore), should change? have absolutely no knowledge javascript, me out here, thank
<div id="test"> <a href="#">sort list</a></div> <ul id="list"> <li><a href="tumblr.com/post/57781372261">peter</a></li> <li><a href="tumblr.com/post/57783141055">mary</a></li> <li><a href="tumblr.com/post/57781372261">paul</a></li> </ul>
when links added, posts sorted numbers there, , not names..
you're sorting whatever between <li>
, </li>
, includes urls, not names. if urls don't sort names, results out of order. in case, you're sorting id numbers in urls.
a simple way solve put names in anchor elements, e.g.
<li><a data-name="peter" href="tumblr.com/post/57781372261">peter</a></li> <li><a data-name="mary" href="tumblr.com/post/57783141055">mary</a></li> <li><a data-name="paul" href="tumblr.com/post/57781372261">paul</a></li>
putting data-name
attribute before href
attribute should make take precedence.
actually, i'm not totally sure work. innerhtml
property contains html after it's been parsed browser, , it's possible reorders attributes. solve this, need provide comparison function sort()
finds names , compares them, rather comparing html directly.
here's version compares text only. works dom nodes themselves, rather converting , html.
function comparetext(a1, a2) { var t1 = a1.innertext, t2 = a2.innertext; return t1 > t2 ? 1 : (t1 < t2 ? -1 : 0); } function sortunorderedlist(ul, sortdescending) { if(typeof ul == "string") { ul = document.getelementbyid(ul); } var lis = ul.getelementsbytagname("li"); var vals = []; for(var = 0, l = lis.length; < l; i++) { vals.push(lis[i]); } vals.sort(comparetext); if(sortdescending) { vals.reverse(); } ul.innerhtml = ''; for(var = 0, l = vals.length; < l; i++) { ul.appendchild(vals[i]); } }
Comments
Post a Comment