How to Sort a List by Alphabetical order?

82 Views Asked by At

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

1

There are 1 best solutions below

0
Webstep Technologies On BEST ANSWER

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