Skip to main content

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 value sort order
> 0 sort a after b, e.g. [b, a]
< 0 sort a before b, e.g. [a, b]
=== 0 keep original order of a and b