Hello All,
Working with HTML and JavaScript, many time we render html in our page with the help of JavaScript, like adding a list that has many list items.
To show that list in a alphabetical order (ascending or descending order) in our HTML page using JavaScript we can use following block of code:
function SortList(elementId) {
var mylist = $("#" + elementId);
$(mylist).children("li").sort(function (item1, item2) {
var compFirst = $(item1).text().toUpperCase();
var compSecond = $(item2).text().toUpperCase();
if (!((compFirst != "") || (compSecond == "DEFAULT"))) {
return (compFirst < compSecond) ? -1 : (compFirst > compSecond) ? 1 : 0;
}
}).appendTo(mylist);
}
In this above function, we are passing the id of the HTML List and by using the sort function of JQuery, we are sorting the elements by comparing each item with other and appending it to list in sorted order.
0 Comment(s)