2

I would like to use CSS to sort my list alphabetically.

For example, suppose I have the following unsorted list

    <ul>
        <li>e </li>
        <li>b </li>
        <li>h </li>
        <li>c </li>
        <li>g </li>
        <li>A </li>
        <li>d </li>
        <li>f </li>
    </ul>

I would like these list items to be sorted alphabetically in my view. How can I achieve this?

Trent
  • 4,208
  • 5
  • 24
  • 46
Kent Davis
  • 27
  • 1
  • 5

1 Answers1

1

Css does not allow you to perform any sort of logic or computation.

You'll need to use JavaScript to achieve the sorting of your list items.

Creating a sorted list with JavaScript

The following code shows an example of initializing a list of unsorted elements, then creating the DOM for a sorted list and appending it to a parent element by ID.

var listElements = [ 'e', 'b', 'h', 'c', 'g', 'A', 'd', 'f' ];

function makeSortedList(array) {
    // Create the list element:
    var list = document.createElement('ul');

    // Sort list items
    array.sort();

    for(var i = 0; i < array.length; i++) {
        // Create the list item
        var item = document.createElement('li');

        // Set list item contents
        item.appendChild(document.createTextNode(array[i]));

        list.appendChild(item);
    }

    return list;
}

// Add sorted list to parent (by id)
document.getElementById('foo').appendChild(makeSortedList(listElements));
Trent
  • 4,208
  • 5
  • 24
  • 46
  • Oh I see jQuery I got from your word yes but wrong answer. I found out and I show you link. https://stackoverflow.com/questions/47484876/ul-and-li-with-jquery-3-2-1-running-error but I don't understand about Dreamweaver cc 2018 did not work. – Kent Davis Nov 25 '17 at 10:25