Sort a list of DOM elements by sorting and calling appendChild()
From an answer by ahuigo on Stack Overflow, here’s a snippet to sort DOM elements:
const list = document.querySelector('ul');
[...list.children]
.sort((a, b) => a.innerText > b.innerText ? 1 : -1)
.forEach(node => list.appendChild(node));
Most of this is syntax I’m already familiar with; the interesting bit is how appendChild() is behaving here:
If the given child is a reference to an existing node in the document,
appendChild()
moves it from its current position to the new position.
By calling this on every node in the list, in sorted order, the nodes get moved into sorted order.
What does 1/-1 returned from the sort comparison mean?
Here’s a table from the MDN docs that explains what the custom sort comparison should return, which I always forget:
compareFn(a, b)
return valuesort order > 0 sort a
afterb
, e.g.[b, a]
< 0 sort a
beforeb
, e.g.[a, b]
=== 0 keep original order of a
andb