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
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