How may I sort a list alphabetically using jQuery?

后端 未结 10 2158
灰色年华
灰色年华 2020-11-21 23:13

I\'m a bit out of my depth here and I\'m hoping this is actually possible.

I\'d like to be able to call a function that would sort all the items in my list alphabeti

10条回答
  •  Happy的楠姐
    2020-11-21 23:40

    HTML

    • alpha
    • gamma
    • beta

    JavaScript

    function sort(ul) {
        var ul = document.getElementById(ul)
        var liArr = ul.children
        var arr = new Array()
        for (var i = 0; i < liArr.length; i++) {
            arr.push(liArr[i].textContent)
        }
        arr.sort()
        arr.forEach(function(content, index) {
            liArr[index].textContent = content
        })
    }
    
    sort("list")
    

    JSFiddle Demo https://jsfiddle.net/97oo61nw/

    Here we are push all values of li elements inside ul with specific id (which we provided as function argument) to array arr and sort it using sort() method which is sorted alphabetical by default. After array arr is sorted we are loop this array using forEach() method and just replace text content of all li elements with sorted content

提交回复
热议问题