How do I sort html list alphabetically using javascript on page load
You did not actually call the sort()
Using spread and a normal sort with a sort function you can shorten your sorting considerable
const sortList = list => [...list].sort((a, b) => {
const A = a.textContent, B = b.textContent;
return (A < B) ? -1 : (A > B) ? 1 : 0;
});
window.addEventListener("load", function() {
const ul = document.getElementById("MYList");
const list = ul.querySelectorAll("li");
ul.append(...sortList(list));
})
h2 {
text-align: center;
}
#MYList {
color: crimson;
list-style-type: none;
list-style-image: none;
list-style-position: outside;
}
<div>
<title> Sort a list alphabetically Using JavaScript </title>
<h2> On pageload, sort the below list </h2>
<ul id="MYList">
<li>Fish</li>
<li>Cat</li>
<li>Animal</li>
<li>Dog</li>
<li>Bird</li>
<li>Eagle</li>
<li>Home</li>
</ul>
</div>
Sort an html list with javascript
This will probably be the fastest way to do it, since it doesn't use jQuery:
function sortList(ul){
var new_ul = ul.cloneNode(false);
// Add all lis to an array
var lis = [];
for(var i = ul.childNodes.length; i--;){
if(ul.childNodes[i].nodeName === 'LI')
lis.push(ul.childNodes[i]);
}
// Sort the lis in descending order
lis.sort(function(a, b){
return parseInt(b.childNodes[0].data , 10) -
parseInt(a.childNodes[0].data , 10);
});
// Add them into the ul in order
for(var i = 0; i < lis.length; i++)
new_ul.appendChild(lis[i]);
ul.parentNode.replaceChild(new_ul, ul);
}
Call the function like:
sortList(document.getElementsByClassName('list')[0]);
You can sort other lists the same way, and if you have other elements on the same page with the list class you should give your ul an id and pass it in using that instead.
Example JSFiddle
Edit
Since you mentioned that you want it to happen on pageLoad, I'm assuming you want it to happen ASAP after the ul is in the DOM which means you should add the function sortList
to the head of your page and use it immediately after your list like this:
<head>
...
<script type="text/javascript">
function sortList(ul){
var new_ul = ul.cloneNode(false);
var lis = [];
for(var i = ul.childNodes.length; i--;){
if(ul.childNodes[i].nodeName === 'LI')
lis.push(ul.childNodes[i]);
}
lis.sort(function(a, b){
return parseInt(b.childNodes[0].data , 10) - parseInt(a.childNodes[0].data , 10);
});
for(var i = 0; i < lis.length; i++)
new_ul.appendChild(lis[i]);
ul.parentNode.replaceChild(new_ul, ul);
}
</script>
</head>
<body>
...
<ul class="list">
<li id="alpha">32</li>
<li id="beta">170</li>
<li id="delta">28</li>
</ul>
<script type="text/javascript">
!function(){
var uls = document.getElementsByTagName('ul');
sortList( uls[uls.length - 1] );
}();
</script>
...
</body>
sorting li elements alphabetically
Instead of lis[i].innerHTML = vals[i];
, sort the lis
list and do ul.appendChild(lis[i])
. This will remove the current li
from its position in the DOM and append it to the end of the ul
. I'm assuming the only li
elements are direct children of the ul
.
function sortList(ul) { var ul = document.getElementById(ul);
Array.from(ul.getElementsByTagName("LI")) .sort((a, b) => a.textContent.localeCompare(b.textContent)) .forEach(li => ul.appendChild(li));}
sortList("stocksymbols");
<ul id=stocksymbols> <li>AAA</li> <li>ZZZ</li> <li>MMM</li> <li>BBB</li></ul>
Sort alphaNumeric HTML list
It would probably be a lot easier to sort the li
s in their own array, outside of the document, and then append them to the ul
again in the correct order. You can use localeCompare
to check which string comes first lexicographically, no jQuery required:
const theList = document.querySelector('.theList');const lis = Array.from(theList.children);const firstText = elm => elm.children[0].textContent;lis.sort((a, b) => firstText(a).localeCompare(firstText(b)));lis.forEach(li => theList.appendChild(li));
<ul class="theList"> <li><b>abc11:</b>Hello</li> <li><b>abc10:</b>Hello</li> <li><b>xyz24:</b>Hello</li> <li><b>abc1:</b>Hello</li> <li><b>xyz2:</b>Hello</li></ul>
Sorting an HTML list ascending and descending, with jQuery
You have to clear your sortedItms
.
var setItems = function () {
sortedItms = [];
for (var j = 0; j < sortedNames.length; j++) {
var sortedItm = '<li>' + sortedNames[j] + '</li>';
sortedItms.push(sortedItm);
}
sortedItms.join('');
$('.list').html(sortedItms);
}
Related Topics
How to Chop/Slice/Trim Off Last Character in String Using JavaScript
JavaScript Get Xpath of a Node
Remove Property for All Objects in Array
Jquery Checkbox Change and Click Event
How to Tell If Caps Lock Is on Using JavaScript
Remove All Elements Contained in Another Array
How to Include a JavaScript Script File in Angular and Call a Function from That Script
Convert Column Index into Corresponding Column Letter
Split a String by Commas But Ignore Commas Within Double-Quotes Using JavaScript
Are Variable Operators Possible
Getting a Better Understanding of Callback Functions in JavaScript
How to Implement Routereusestrategy Shoulddetach for Specific Routes in Angular 2
Change Values in Array When Doing Foreach
Why How to Use a Function Before It's Defined in JavaScript
Firing Event on Dom Attribute Change
Securityerror: the Operation Is Insecure - Window.History.Pushstate()