ProgrammerPickleRick
ProgrammerPickleRick

Reputation: 35

How do I alphabetically sort a list in HTML with jQuery?

I have 2 html files index.html and list.html. When i load the list.html to index.html I want it automatically sort to alphabetical.

index.html:

<button onclick="javascript:showlist()">Show</button>
<div id="content"></div>

list.html:

<ul id="myUL">
<li>SUPERMAN</li>
<li>BATMAN</li>
<li>FLASH</li>
<li>ANARKY</li>
</ul>

js:

function showlist(){
  $("#content").load("list.html");
  sortList();
}

function sortList() {
  var list, i, switching, b, shouldSwitch;
  list = document.getElementById("myUL");
  switching = true;
  /* Make a loop that will continue until
  no switching has been done: */
  while (switching) {
    // start by saying: no switching is done:
    switching = false;
    b = list.getElementsByTagName("li");
    // Loop through all list-items:
    for (i = 0; i < (b.length - 1); i++) {
      // start by saying there should be no switching:
      shouldSwitch = false;
      /* check if the next item should
      switch place with the current item: */
      if (b[i].innerHTML.toLowerCase() > b[i + 1].innerHTML.toLowerCase()) {
        /* if next item is alphabetically
        lower than current item, mark as a switch
        and break the loop: */
        shouldSwitch = true;
        break;
      }
    }
    if (shouldSwitch) {
      /* If a switch has been marked, make the switch
      and mark the switch as done: */
      b[i].parentNode.insertBefore(b[i + 1], b[i]);
      switching = true;
    }
  }
}

Upvotes: 3

Views: 206

Answers (3)

poorly-written-code
poorly-written-code

Reputation: 1073

As the accepted answer mentions, you have to run your sort code in the .load() callback. But I'm going to answer again anyway because that is some narley sorting code you have there. You can use .append(), .detach() and .sort() for much cleaner code.

$('#content').load('list.html', function() {
  $('ul').append($('li').detach().sort((a, b) => a.textContent > b.textContent));
});

Upvotes: 0

Mister Jojo
Mister Jojo

Reputation: 22431

you can't sort your list before when it was loaded
you need to use the event load over your div
code it this way:

function showlist() {
  $('#content').load('list.html');
}

const contentDiv = document.querySelector('#content')

contentDiv.onload =_=> 
  {
  const
    list  = contentDiv.querySelector(`ul`)
  , arrLI = [...list.querySelectorAll('li')]
      .map(li=>({key:li.textContent.toLowerCase(),li}))
      .sort((a,b)=>a.key.localeCompare(b.key))

  arrLI.forEach(el=>list.appendChild(el.li) ) 
  }

here is the code to demonstrate how the sort works:

sortList('#content')

function sortList( parentDiv )
  {
  const
    list  = document.querySelector(`${parentDiv} > ul`)
  , arrLI = [...list.querySelectorAll('li')]
      .map(li=>({key:li.textContent.toLowerCase(),li}))
      .sort((a,b)=>a.key.localeCompare(b.key))

  arrLI.forEach(el=>list.appendChild(el.li) ) 
  }
<div id="content">
  <ul>
    <li>SUPERMAN</li>
    <li>BATMAN</li>
    <li>FLASH</li>
    <li>ANARKY</li>
  </ul>
</div>

Upvotes: 2

Kinglish
Kinglish

Reputation: 23664

The part that's missing is the onload handler. Without that, you're probably calling sortList() before the content has loaded. Otherwise your function works

$("#content").load("list.html", function() {
    console.log("Loaded");
    sortList();
})

Upvotes: 3

Related Questions