How to sort an HTML list using JavaScript?

HTMLWeb DevelopmentFront End TechnologyJavascript

To sort an HTML list using JavaScript, the code is as follows −

Example

 Live Demo

<!DOCTYPE html>
<html>
<body>
<h1>Sorting list example</h1>
<button>Click to sort</button>
<ul class="animalList">
<li>Giraffe</li>
<li>Camel</li>
<li>Dog</li>
<li>Lion</li>
<li>Cheetah</li>
<li>Cat</li>
</ul>
<script>
   document .getElementsByTagName("button")[0] .addEventListener("click", sortList);
   function sortList() {
      var list, i, sortFlag, LiEle, sorted;
      list = document.querySelector(".animalList");
      sortFlag = true;
      while (sortFlag) {
         sortFlag = false;
         LiEle = list.getElementsByTagName("LI");
         for (i = 0; i < LiEle.length - 1; i++) {
            sorted = false;
            if ( LiEle[i].innerHTML.toLowerCase() > LiEle[i + 1].innerHTML.toLowerCase() ) {
               sorted = true;
               break;
            }
         }
         if (sorted) {
            LiEle[i].parentNode.insertBefore(LiEle[i + 1], LiEle[i]);
            sortFlag = true;
         }
      }
   }
</script>
</body>
</html>

Output

The above code will produce the following output −

On clicking the “Click to sort” button −

raja
Published on 06-May-2020 17:59:00
Advertisements