How to sort an HTML list with JavaScript?

Sometimes, we want to sort an HTML list with JavaScript.

In this article, we’ll look at how to sort an HTML list with JavaScript.

How to sort an HTML list with JavaScript?

To sort an HTML list with JavaScript, we can convert select the li elements, convert the node list of li elements into an array, do the sorting, and then replace the ul content with replaceChildren.

For instance, we write:

<button>
  sort
</button>
<ul>
  <li>32</li>
  <li>170</li>
  <li>28</li>
</ul>

to add a button and a list.

Then we write:

const button = document.querySelector('button')
const ul = document.querySelector('ul')
const lis = document.querySelectorAll('li')
button.onclick = () => {
  const sortedLis = [...lis].sort((a, b) => +a.textContent - +b.textContent)
  ul.replaceChildren(...sortedLis)
}

to select the button and ul with querySelector.

And we select the li’s with querySelectorAll.

Next, we set button.onclick to a function to sort the li’s when the button is clicked.

To sort them, we spread the lis into an array.

Then we call sort with a callback that sort the textContent of each entry converted to numbers with +.

And then we replace the existing li entries in the ul with the sorted ones by calling ul.replaceChildren with the entries from sortedLis.

They’ll be inserted in the same order they’re listed in the arguments.

Therefore, once we click sort, we see:

28
32
170

displayed.

Conclusion

To sort an HTML list with JavaScript, we can convert select the li elements, convert the node list of li elements into an array, do the sorting, and then replace the ul content with replaceChildren.