Categories
JavaScript Answers

How to sort of HTML elements with JavaScript?

Spread the love

Sometimes, we want to sort of HTML elements with JavaScript.

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

How to sort of HTML elements with JavaScript?

To sort of HTML elements with JavaScript, we can select them. Then we can spread the selected elements into an array and use the array sort method to do the sorting.

For instance, we write:

<ol>
  <li>foo</li>
  <li>bar</li>
  <li>baz</li>
</ol>

to add 3 li elements.

Then we write:

const lis = document.querySelectorAll('li')
const sorted = [...lis]
  .sort((a, b) => {
    return a.innerHTML.localeCompare(b.innerHTML)
  })
console.log(sorted)

to select the li’s with querySelectorAll.

Then we spread the li elements into an array.

Next, we call sort with a callback that compares the innerHTML of each with localeCompare to sort them alphabetically.

Therefore, sorted is an array of li elements with the one with bar first, the one with baz 2nd, and the one with foo last.

Conclusion

To sort of HTML elements with JavaScript, we can select them. Then we can spread the selected elements into an array and use the array sort method to do the sorting.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *