This works for any number of lists: it basically gathers all li
s in ul
s that have your attribute, sorts them according to their data-*
attribute value and re-appends them to their parent.
Array.from(document.querySelectorAll("ul > li[data-azsort]"))
.sort(({dataset: {azsort: a}}, {dataset: {azsort: b}}) => a.localeCompare(b)) // To reverse it, use `b.localeCompare(a)`.
.forEach((item) => item.parentNode.appendChild(item));
-
Jon Skeet
Stack Overflow user
-
John Smith
Professor
-
Tom Barnes
Lecturer
-
John Smith
Professor
-
Tom Barnes
Lecturer
-
Jon Skeet
Stack Overflow user
The funny thing is, it gets all li
s in the same array, sorts them all, but in the end figures out which list the li
originally belonged to. It’s a pretty simple and straight-forward solution.
A slightly longer ECMAScript 5.1 alternative would be:
Array.prototype.slice.call(document.querySelectorAll("ul > li[data-azsort]")).sort(function(a, b) {
a = a.getAttribute("data-azsort");
b = b.getAttribute("data-azsort");
return a.localeCompare(b);
}).forEach(function(node) {
node.parentNode.appendChild(node);
});