0

I have an unordered list on my page. I will be adding more names to it continuously, so I want the list to be sorted alphabetically on page load.

Here is what I have done so far but it is not working.

What is wrong here, how can I make this script sort the list alphabetically?

function sort() {

  // Declaring Variables
  var MY_list, i, run, li, stop;

  // Taking content of list as input
  MY_list = document.getElementById("MYList");

  run = true;

  while (run) {
    run = false;
    li = MY_list.getElementsByTagName("LI");

    // Loop traversing through all the list items
    for (i = 0; i < (li.length - 1); i++) {
      stop = false;
      if (li[i].innerHTML.toLowerCase() >
        li[i + 1].innerHTML.toLowerCase()) {
        stop = true;
        break;
      }
    }

    /* If the current item is smaller than
    the next item then adding it after
    it using insertBefore() method */
    if (stop) {
      li[i].parentNode.insertBefore(
        li[i + 1], li[i]);

      run = true;
    }
  }
}
sort()
<div style="text-align: left;">
  <title> Sort a list alphabetically Using JavaScript </title>
  <h2 style="text-align: center;"> On pageload,&nbsp; sort the below list </h2>
  <ul style="color: crimson; list-style-type: none; list-style-image: none; list-style-position: 
    outside;" 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>
<hr/>
<div style="text-align: center;">
  <div style="text-align: center;">
    <dl>
      <dt><big><big><big><a
    style="text-decoration: none;" href="A-LIST.html">A</a>
    <a style="text-decoration: none;" href="B-LIST.html">B</a>
    <a style="text-decoration: none;" href="C-LIST.html">C</a>
    <a style="text-decoration: none;" href="D-LIST.html">D</a>
    <a style="text-decoration: none;" href="E-LIST.html">E</a>
    <a style="text-decoration: none;" href="F-LIST.html">F</a>
    <a style="text-decoration: none;" href="G-LIST.html">G</a>
    <a style="text-decoration: none;" href="H-LIST.html">H</a>
    <a style="text-decoration: none;" href="I-LIST.html">I</a>
    <a style="text-decoration: none;" href="J-LIST.html">J</a>
    <a style="text-decoration: none;" href="K-LIST.html">K</a>
    <a style="text-decoration: none;" href="L-LIST.html">L</a>
    <a style="text-decoration: none;" href="M-LIST.html">M</a>
    <a style="text-decoration: none;" href="N-LIST.html">N</a>
    <a style="text-decoration: none;" href="O-LIST.html">O</a>
    <a style="text-decoration: none;" href="P-LIST.html">P</a>
    <a style="text-decoration: none;" href="Q-LIST.html">Q</a>
    <a style="text-decoration: none;" href="R-LIST.html">R</a>
    <a style="text-decoration: none;" href="S-LIST.html">S</a>
    <a style="text-decoration: none;" href="T-LIST.html">T</a>
    <a style="text-decoration: none;" href="U-LIST.html">U</a>
    <a style="text-decoration: none;" href="V-LIST.html">V</a>
    <a style="text-decoration: none;" href="W-LIST.html">W</a>
    <a style="text-decoration: none;" href="X-LIST.html">X</a>
    <a style="text-decoration: none;" href="Y-LIST.html">Y</a>
    <a style="text-decoration: none;" href="Z-LIST.html">Z</a></big></big></big></dt>
    </dl>
  </div>
</div>

3
  • 1
    I made you a snippet. I had to add }} to the end Commented Jan 14, 2022 at 13:32
  • Please share more details. What do you mean by "not working"? What exactly is not working? Sorting the list? Sorting it on page load? Commented Jan 14, 2022 at 13:35
  • 3
    You did not call sort Commented Jan 14, 2022 at 13:54

2 Answers 2

3

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,&nbsp; 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>

Sign up to request clarification or add additional context in comments.

3 Comments

Thank you. this is very helpful. Now I have this issue; if I put the code in the same file with HTML, it works fine. If I put the code in a different .js file and link to the HTML, it doesn't work. I know I must be omitting something or doing it the wrong way. Here is my reference to the javascript file <script src="./sortlist.js"></script> Both the HTML and the javascript files are in the same folder.
Now it works. Your answer solved it.
Yeah, the window.addeventListener is used to allow the script to be anywhere in the page or linked in the page
0

Maybe this is my Angular approach speaking, but I would do it this way :

  1. Read your list and store all the names in an array
  2. Clear the HTML list
  3. Sort the JS list
  4. Rebuild the list from the sorted array

let names = [];
const elems = document.getElementsByTagName("li");

for(let elem of elems){
  names.push(elem.innerHTML);
}

MYList.innerHTML="";
names.sort();

for(let name of names){
  MYList.innerHTML += `<li>${name}</li>`
}
<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>

Of course, a cleverer approach would be to not have the list already hardcoded in HTML, but stored in an array in JS, and use this array to build your view (again, Angular habit)

1 Comment

Thank you. That sounds interesting. I will give it a try

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.