The neatest way I can think of:
The param compare
is just like the compare function used in Array.sort().
Sort child nodes.
/**
* @param {!Node} parent
* @param {function(!Node, !Node):number} compare
*/
function sortChildNodes(parent, compare) {
const moveNode = (newParent, node) => {
// If node is already under a parent, append() removes it from the
// original parent before appending it to the new parent.
newParent.append(node);
return newParent;
};
parent.append(Array.from(parent.childNodes) // Shallow copies of nodes.
.sort(compare) // Sort the shallow copies.
.reduce(moveNode, document.createDocumentFragment()));
}
Sort child elements (a subset of child nodes).
/**
* @param {!Element} parent
* @param {function(!Element, !Element):number} compare
*/
function sortChildren(parent, compare) {
const moveElement = (newParent, element) => {
// If element is already under a parent, append() removes it from the
// original parent before appending it to the new parent.
newParent.append(element);
return newParent;
};
parent.append(Array.from(parent.children) // Shallow copies of elements.
.sort(compare) // Sort the shallow copies.
.reduce(moveElement, document.createDocumentFragment()));
}