JavaScript sort list

This page discusses - 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:

<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;
for(var i=0; i<listLength; i++)
listItem[i].firstChild.nodeValue = list[i];
<body onload="sortList();">
<ul id="list">


Output will be displayed as:

Download Source Code:


Share on Google+Share on Google+

JavaScript sort list

Posted on: April 18, 2011 If you enjoyed this post then why not add us on Google+? Add us to your Circles



Discuss: JavaScript sort list  

Post your Comment

Your Name (*) :
Your Email :
Subject (*):
Your Comment (*):
  Reload Image
August 27, 2012
Sort value and style?

Very helpful! But what if we want to sort the value /and/ the style? With the code presented, the sorting is correct, but only the 'value' will be sorted. If the 'style' of the nodes is different, that will stay. For example: <ul id="list"> <li style="font-weight: bold">Tina</li> <li>Sania</li> <li class="angerlina-class">Angelina</li> <li>Martina</li> <li>Simran</li> </ul> will result in: <ul id="list"> <li style="font-weight: bold">Angelina</li> <li>Martina</li> <li class="angerlina-class">Sania</li> <li>Simran</li> <li>Tina</li> </ul> How can I make this turn into: <ul id="list"> <li class="angerlina-class">Angelina</li> <li>Martina</li> <li>Sania</li> <li>Simran</li> <li style="font-weight: bold">Tina</li> </ul> ? Thank you!