My question is very similar to a number of others I've found on Stack Overflow, but not quite the same.
I'd like to sort list items based on the content of a span contained within each item -- but using a sort order that I can define. Here's the HTML for a sample list item:
<li>
<span class=fname>John</span>
<span class=lname>Doe</span>
<span class=year>Sophomore</span>
</li>
I want to sort based on the content of the year span, but chronologically rather than alphabetically. The order, obviously, needs to be:
- Freshman
- Sophomore
- Junior
- Senior
How can I do this?
Just for reference, I'm using the following jQuery code (which works perfectly) to sort alphabetically by last name:
function sortByLastName(){
var myList = $('#foo ul');
var listItems = myList.children('li').get();
listItems.sort(function(a,b){
var compA = $(a).find('.lname').text().toUpperCase();
var compB = $(b).find('.lname').text().toUpperCase();
return (compA < compB) ? -1 : (compA > compB) ? 1 : 0;
});
$(myList).append(listItems);
};