How to create a filter list with JavaScript?

JavascriptWeb DevelopmentObject Oriented Programming

To create a filter list with JavaScript, the code is as follows −

Example

 Live Demo

<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1" />
<style>
   * {
      box-sizing: border-box;
   }
   .searchInput {
      width: 100%;
      font-size: 16px;
      padding: 12px 20px 12px 40px;
      border: 2px solid grey;
      margin-bottom: 12px;
   }
   .animalUL {
      list-style-type: none;
      padding: 0;
      margin: 0;
   }
   .animalUL li a {
      border-top: 1px solid rgb(0, 0, 0);
      margin-top: -1px;
      background-color: #f6f6f6;
      padding: 12px;
      text-decoration: none;
      font-size: 18px;
      color: black;
      display: block;
   }
   .animalUL li a:hover:not(.header) {
      background-color: #eee;
   }
</style>
</head>
<body>
<h1>Filter list example</h1>
<input type="text" class="searchInput" onkeyup="filterFunction()" placeholder="Search for animals" title="Type in a name"/>
<ul class="animalUL">
<li><a href="#">Cat</a></li>
<li><a href="#">Cheetah</a></li>
<li><a href="#">Dog</a></li>
<li><a href="#">Giraffe</a></li>
<li><a href="#">Lion</a></li>
<li><a href="#">Leopard</a></li>
<li><a href="#">llama</a></li>
</ul>
<script>
   function filterFunction() {
      var input, filter, ul, li, a, i, value;
      input = document.querySelector(".searchInput");
      filter = input.value.toUpperCase();
      ul = document.querySelector(".animalUL");
      li = ul.getElementsByTagName("li");
      for (i = 0; i < li.length; i++) {
         a = li[i].getElementsByTagName("a")[0];
         value = a.textContent || a.innerText;
         if (value.toUpperCase().indexOf(filter) > -1) {
            li[i].style.display = "";
         } else {
            li[i].style.display = "none";
         }
      }
   }
</script>
</body>
</html>

Output

The above code will produce the following output −

On typing something in the search field −

raja
Published on 06-May-2020 14:14:00
Advertisements