How to search for items in a dropdown menu with CSS and JavaScript?

CSSWeb DevelopmentFront End TechnologyJavascript

To search for items in a dropdown menu with CSS and JavaScript, the code is as follows −


 Live Demo

<!DOCTYPE html>
<meta name="viewport" content="width=device-width, initial-scale=1">
   .dropbtn {
      background-color: rgb(76, 78, 175);
      color: white;
      padding: 16px;
      font-size: 16px;
      border: none;
      cursor: pointer;
   .dropbtn:hover, .dropbtn:focus {
      background-color: #4f3e8e;
   .searchField {
      box-sizing: border-box;
      font-size: 16px;
      padding: 14px 20px 12px 45px;
      border: none;
      border-bottom: 1px solid #ddd;
   .searchField:focus {outline: 3px solid #ddd;}
   .dropdown {
      position: relative;
      display: inline-block;
   .dropdownList {
      display: none;
      position: absolute;
      background-color: #f6f6f6;
      min-width: 230px;
      overflow: auto;
      border: 1px solid #ddd;
      z-index: 1;
   .dropdownList a {
      color: black;
      padding: 12px 16px;
      text-decoration: none;
      display: block;
   .dropdown a:hover {background-color: #ddd;}
   .show {display: block;}
<h1>Search/filterText Dropdown Example</h1>
<div class="dropdown">
<button class="dropbtn" onclick="showDropList()">Dropdown</button>
<div id="myDropdown" class="dropdownList">
<input type="text" placeholder="Search.." class="searchField">
<a href="#">Cow</a>
<a href="#">Cat</a>
<a href="#">Dog</a>
<a href="#">Giraffe</a>
<a href="#">Lion</a>
<a href="#">Leopard</a>
<a href="#">Cheetah</a>
   function showDropList(){
      let dropDiv = document.querySelector('.dropdownList');
      if("block"){ = "";
      } else { = "block";
   function filterDropdown() {
      var inputSearch, filterText, ul, li, links, i,div;
      inputSearch = document.querySelector(".searchField");
      filterText = inputSearch.value.toUpperCase();
      div = document.getElementById("myDropdown");
      links = div.getElementsByTagName("a");
      for (i = 0; i < links.length; i++) {
         txtValue = links[i].textContent || links[i].innerText;
         if (txtValue.toUpperCase().indexOf(filterText) > -1) {
            links[i].style.display = "";
         } else {
         links[i].style.display = "none";


The above code will produce the following output −

On clicking the Dropdown button and entering text in search field −

Updated on 06-May-2020 14:27:03