Sometimes, we want to sort DOM nodes with JavaScript.
In this article, we’ll look at how to sort DOM nodes with JavaScript.
How to sort DOM nodes with JavaScript?
To sort DOM nodes with JavaScript, we convert the node list to an array.
For instance, we write
const list = document.querySelector("#test-list");
[...list.children]
.sort((a, b) => (a.innerText > b.innerText ? 1 : -1))
.forEach((node) => list.appendChild(node));
to select the element with ID test-list
with querySelector
.
Then we get the child elements of it as a node list with list.children
.
Next, we convert the node list to an array with the spread operator.
And then we call sort
with a callback to sort the nodes by their innerText
values and return the sorted array.
Finally, we call forEach
to loop through each node.
Conclusion
To sort DOM nodes with JavaScript, we convert the node list to an array.