Skip to content Skip to sidebar Skip to footer

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

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:

  1. Sort the list (using .sort() method)
  2. Create the titles.

Read the code and let me know if something not clear.

var list = $('ul'),
    items = $('li', list);

// sort the list
var 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 titles
var 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;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul>
  <li><a href="#/"> john-smith/</a></li>
  <li><a href="#/"> joe-smith/</a></li>
  <li><a href="#/"> glen-smith/</a></li>
  <li><a href="#/"> daniel-smith/</a></li>
  <li><a href="#/"> 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 character
var current_letter='1';
//loop through each row of the sorted array
for (var i = 0; i < a.length; i++) {
  //if a new first character is detected, add its corresponding html
   if(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"