Skip to main content

Sorting Elements in JavaScript DOM (Live Playground)

In this tutorial, we will learn how to sort elements in JavaScript DOM using simple techniques to improve the readability and user experience of your web applications.

Example: Sorting List Items Alphabetically

Let's consider the following unordered list with unordered items:

<ul id="fruit-list">
<li>Orange</li>
<li>Apple</li>
<li>Banana</li>
<li>Pineapple</li>
<li>Grapes</li>
</ul>

We will now sort the list items alphabetically:

const fruitList = document.getElementById('fruit-list');
const listItems = Array.from(fruitList.getElementsByTagName('li'));

listItems.sort((a, b) => a.textContent.localeCompare(b.textContent));

fruitList.innerHTML = '';

listItems.forEach(item => {
fruitList.appendChild(item);
});

After executing this code, the updated HTML structure will be:

<ul id="fruit-list">
<li>Apple</li>
<li>Banana</li>
<li>Grapes</li>
<li>Orange</li>
<li>Pineapple</li>
</ul>

In this example, we used the following steps to sort the list items alphabetically:

  1. Get the list element using getElementById.
  2. Get the list items and convert them to an array using Array.from.
  3. Sort the list items using the sort method and the localeCompare function for string comparison.
  4. Clear the original list items using innerHTML.
  5. Append the sorted list items to the list using appendChild.
Live Playground, Try it Yourself

Conclusion

In this tutorial, we have learned how to sort elements in JavaScript DOM using simple techniques. Sorting elements can improve the readability and user experience of your web applications, making it easier for users to find and navigate through the content.