i would like to make a list in cargo collective, and make them automatically sort in alphabetical order by the first character. Now i have two versions of JavaScript coding, but they can not include uppercase and lowercase at the same time.
html is like this:
two versions of javascript:
the first one
<script type="text/javascript">
$("li").sort(function(a, b) {
var aText = $(a).text(), bText = $(b).text();
return aText < bText ? -1 : aText > bText ? 1 : 0;}).appendTo('ul');
</script>
the second one
<script type="text/javascript">
var list = document.getElementById('mylist');
var items = list.childNodes;
var itemsArr = [];
for (var i in items) {
if (items[i].nodeType == 1) { // get rid of the whitespace text nodes
itemsArr.push(items[i]);
}
}
itemsArr.sort(function(a, b) {
return a.innerHTML == b.innerHTML
? 0
: (a.innerHTML > b.innerHTML ? 1 : -1);
});
for (i = 0; i < itemsArr.length; ++i) {
list.appendChild(itemsArr[i]);
}
</script>
How to make the bottom lowercase words also in the list, not separate them...
thanks!!!
In the second script, apply toUpperCase() to both texts before comparing them, or -- a bit more fancy -- you could use the options argument of the localeCompare method:
var list = document.getElementById('mylist');
var itemsArr = Array.from(list.children)
.filter(li => li.textContent.trim()); // Only non-empty
itemsArr.sort(function(a, b) {
return a.textContent.localeCompare(b.textContent, "en", { sensitivity: "base" });
});
// Optionally remove items first? (So empty items are gone?)
list.innerHTML = "";
for (let item of itemsArr) {
list.appendChild(item);
}
<ul id="mylist">
<li></li>
<li></li>
<li></li>
<li>apple Juice</li>
<li>water</li>
<li>lemon</li>
<li>Icetea</li>
<li>cola</li>
<li>Tonic</li>
<li></li>
</ul>