Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

244
Visualizações
sorting <li> elements alphabetically in cargo collective

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:

html code

two versions of javascript:

the first one

js-1

<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

js-2

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

both result like this

How to make the bottom lowercase words also in the list, not separate them...

thanks!!!

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

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>

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda