Latest Tutorials| Questions and Answers|Ask Questions?|Site Map



Home Javascript Javascriptexamples JavaScript sort list

Related Tutorials


 
 

Share on Google+Share on Google+

JavaScript sort list

Advertisement
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:

<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:

        

Advertisements

If you enjoyed this post then why not add us on Google+? Add us to your Circles



Liked it!  Share this Tutorial


Follow us on Twitter, or add us on Facebook or Google Plus to keep you updated with the recent trends of Java and other open source platforms.

Posted on: April 18, 2011

Related Tutorials

Discuss: JavaScript sort list  

Post your Comment


Your Name (*) :
Your Email :
Subject (*):
Your Comment (*):
  Reload Image
 
 
Comments:1
Wim
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!
DMCA.com