Alphabetically Order Html List With Headers
I am looking to Alphabetically order an HTML list, but after each letter, there would be a
tag and a header, indicating the new letter list. To revise if I wasn't clea
tag and a header, indicating the new letter list. To revise if I wasn't clea
Solution 1:
Since putting h3
and hr
inside a ul
tag is not valid, I created this style with css. Just added a li
node with splitter
class.
The solution has 2 steps:
- Sort the list (using
.sort()
method) - Create the titles.
Read the code and let me know if something not clear.
var list = $('ul'),
items = $('li', list);
// sort the listvar sortedItems = items.get().sort(function(a, b) {
var aText = $.trim($(a).text().toUpperCase()),
bText = $.trim($(b).text().toUpperCase());
return aText.localeCompare(bText);
});
list.append(sortedItems);
// create the titlesvar lastLetter = '';
list.find('li').each(function() {
var $this = $(this),
text = $.trim($this.text()),
firstLetter = text[0];
if (firstLetter != lastLetter) {
$this.before('<li class="splitter">' + firstLetter);
lastLetter = firstLetter;
}
});
.splitter {
border-top: 1px solid;
font-size: 1.25em;
list-style: none;
padding-top: 10px;
text-transform: uppercase;
padding-bottom: 10px;
margin-top: 10px;
}
<scriptsrc="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><ul><li><ahref="#/"> john-smith/</a></li><li><ahref="#/"> joe-smith/</a></li><li><ahref="#/"> glen-smith/</a></li><li><ahref="#/"> daniel-smith/</a></li><li><ahref="#/"> johnny-smith/</a></li></ul>
Solution 2:
You need jquery and the following code, but please be sure to remove the space from each row of the above list (before the names) :
var a = [];
//Loop through each row
$( "li" ).each(function( index ) {
//populate the array with their names
a.push($( this ).text());
});
//Alphabetically sort the array
a.sort();
//Clear the existing list
$("ul").html("");
//Start with a random charactervar current_letter='1';
//loop through each row of the sorted arrayfor (var i = 0; i < a.length; i++) {
//if a new first character is detected, add its corresponding htmlif(a[i].charAt(0)!=current_letter){
$("ul").append("<hr /><h3>"+a[i].charAt(0)+"</h3>");
current_letter=a[i].charAt(0);
}
//add the list item to the list
$("ul").append("<li><a href='#/'>"+a[i]+"</a></li>");
}
Post a Comment for "Alphabetically Order Html List With Headers"