CSS make sort alphabetically. Where can I get word?

Viewed 4452

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?

1 Answers

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));
Related