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:
- Get the list element using
getElementById
. - Get the list items and convert them to an array using
Array.from
. - Sort the list items using the
sort
method and thelocaleCompare
function for string comparison. - Clear the original list items using
innerHTML
. - 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.