javascript - Sorting a list by data-attribute -
i have list of people job titles sorted persons’ first names, this:
<ul> <li data-azsort="smithjohn"> <a href="#"> <span class="list-name">john smith</span> </a> <span class="list-desc">professor</span> </li> .. <li data-azsort="barnestom"> <a href="#"> <span class="list-name">tom barnes</span> </a> <span class="list-desc">lecturer</span> </li> </ul>
i’ve added data-azsort
attribute <li>
element, , i’d pop these list elements array, , sort based on data-*
attribute (using plain javascript).
what best way sort list data-azsort
(a-z), returning same code? javascript only, no jquery, etc.
this works number of lists: gathers li
s in ul
s have attribute, sorts them according attribute value , re-appends them parent.
array.prototype.slice.call(document.queryselectorall('ul>li[data-azsort]')).sort(function(a, b) { = a.getattribute('data-azsort'); b = b.getattribute('data-azsort'); return a.localecompare(b); }).foreach(function(a) { a.parentnode.appendchild(a); });
<ul> <li data-azsort="smithjohn"> <a href="#"> <span class="list-name">john smith</span> </a> <span class="list-desc">professor</span> </li> <li data-azsort="xufox"> <a href="#"> <span class="list-name">xufox</span> </a> <span class="list-desc">stackoverflow user</span> </li> <li data-azsort="barnestom"> <a href="#"> <span class="list-name">tom barnes</span> </a> <span class="list-desc">lecturer</span> </li> </ul> <ul> <li data-azsort="smithjohn"> <a href="#"> <span class="list-name">john smith</span> </a> <span class="list-desc">professor</span> </li> <li data-azsort="barnestom"> <a href="#"> <span class="list-name">tom barnes</span> </a> <span class="list-desc">lecturer</span> </li> <li data-azsort="xufox"> <a href="#"> <span class="list-name">xufox</span> </a> <span class="list-desc">stackoverflow user</span> </li> </ul>
the funny thing is, gets li
s in same array, sorts them all, in end figures out list li
belonged to. it’s pretty simple , straight-forward solution.
Comments
Post a Comment