JavaScript sort list

This page discusses - JavaScript sort list

JavaScript sort list

JavaScript sort list

        

In this section, we are going to sort the html list using JavaScript.

You can see in the given example, we have created an unordered list using the <li>with <ul> html tag. The method document.getElementById() defined in the function grabs the id of the list and stores it into the variable listItem which uses the length property to get all the list elements. Then, the listItem[i].firstChild.nodeValue reads the node value of list elements into array and the Javascript method sort() sorts the array. Then in order to update the node values of list element we have used listItem[i].firstChild.nodeValue and stored the sorted list into the variable list[i].

Here is the code:

<html>
<h2>Sorted List</h2>
<script type="text/javascript">
function sortList() {
var listItem = document.getElementById('list').getElementsByTagName('li');
var listLength = listItem.length;
var list = [];
for(var i=0; i<listLength; i++)
list[i] = listItem[i].firstChild.nodeValue;
list.sort();
for(var i=0; i<listLength; i++)
listItem[i].firstChild.nodeValue = list[i];
}
</script>
<body onload="sortList();">
<ul id="list">
<li>Tina</li>
<li>Sania</li>
<li>Angelina</li>
<li>Martina</li>
<li>Simran</li>
</ul>
</body>
</html>

 

Output will be displayed as:

Download Source Code: