wolverine87 wolverine87 - 2 years ago 122
Javascript Question

Sort an unordered list alphabetically

I want to sort an unordered list alphabetically. I've tried many different javascript solutions, not one of them worked (tested in Safari and Chrome). This is the code I would like to use:

var activeLanguage = "de"

function sortUL(selector) {
var $ul = $(selector);
$ul.find('li').sort(function(a, b) {
var upA = $(a).text().toUpperCase();
var upB = $(b).text().toUpperCase();
return (upA < upB) ? -1 : (upA > upB) ? 1 : 0;

$(document).ready(function() {

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<ul id="WoodList">

The list remains unsorted in the browser. Why is it not working ?

Answer Source

Here's a working example on JSFiddle: https://jsfiddle.net/vzbgzexc/

Make sure that you're loading jQuery. It doesn't look like anywhere in your code that you're loading jQuery, yet you're using $. You're likely receiving an error in your browser's console similar to this:

ReferenceError: $ is not defined


<script src="https://code.jquery.com/jquery-3.0.0.min.js"></script>

Hope that helps!

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download