skip to Main Content

what is the Javascript code for sorting an HTML list alphabetically?
for example:

NBA Teams:
- Sacramento Kings
- Chicago Bulls
- Atlanta Hawks
- Indiana Pacers
- LA Lakers
- Boston Celtics

I want to make the list automatically sorted alphabetically after loading the page (without the need to press a button).

so the result will be:

- Atlanta Hawks
- Boston Celtics
- Chicago Bulls
- Indiana Pacers
- LA Lakers
- Sacramento Kings

this is close to what i want but with a button
https://www.w3schools.com/howto/howto_js_sort_list.asp

2

Answers


  1. <!DOCTYPE html>
    <html lang="en">
    <head>
      <meta charset="UTF-8">
      <meta name="viewport" content="width=device-width, initial-scale=1.0">
      <title>NBA Teams</title>
      <script>
        document.addEventListener("DOMContentLoaded", function () {
          var teamList = document.getElementById("teamList");
          var teams = Array.from(teamList.children);
          teams.sort(function (a, b) {
            return a.textContent.localeCompare(b.textContent);
          });
          teamList.innerHTML = "";
          teams.forEach(function (team) {
            teamList.appendChild(team);
          });
        });
      </script>
    </head>
    <body>
      <h2>NBA Teams:</h2>
      <ul id="teamList">
        <li>Sacramento Kings</li>
        <li>Chicago Bulls</li>
        <li>Atlanta Hawks</li>
        <li>Indiana Pacers</li>
        <li>LA Lakers</li>
        <li>Boston Celtics</li>
      </ul>
    </body>
    </html>
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search