How to filter/search a list

Learn how to use JavaScript to create a filter list.

Filter list

How to use JavaScript to search for items in a list.

Try it yourself

Create a search list

Step 1 - Add HTML:

<input type="text" id="myInput" onkeyup="myFunction()" placeholder="Search for names..">
<ul id="myUL">
  <li><a href="#">Adele</a></li>
  <li><a href="#">Agnes</a></li>
  <li><a href="#">Billy</a></li>
  <li><a href="#">Bob</a></li>
  <li><a href="#">Calvin</a></li>
  <li><a href="#">Christina</a></li>
  <li><a href="#">Cindy</a></li>
</ul>

Note:In this demonstration, we use href="#" because we don't have a page to link to. In actual application, this should point to a real URL of a specific page.

Step 2 - Add CSS:

Set the styles for the input element and the list:

#myInput {
  background-image: url('/css/searchicon.png'); /* Add a search icon to the input box */
  background-position: 10px 12px; /* Position the search icon */
  background-repeat: no-repeat; /* Do not repeat icon images */
  width: 100%; /* Full width */
  font-size: 16px; /* Increase font size */
  padding: 12px 20px 12px 40px; /* Add some inner padding */
  border: 1px solid #ddd; /* Add a grey border */
  margin-bottom: 12px; /* Add some space below the input box */
}
#myUL {
  /* Remove the default list style */
  list-style-type: none;
  padding: 0;
  margin: 0;
}
#myUL li a {
  border: 1px solid #ddd; /* Add border to all links */
  margin-top: -1px; /* Prevent double borders */
  background-color: #f6f6f6; /* Grey background color */
  padding: 12px; /* Add some inner padding */
  text-decoration: none; /* Remove default text underline */
  font-size: 18px; /* Increase font size */
  color: black; /* Add black text color */
  display: block; /* Make it a block-level element to fill the entire list */
}
#myUL li a:hover:not(.header) {
  background-color: #eee; /* Add hover effect to all links (except headers) */
}

Step 3 - Add JavaScript:

<script>
function myFunction() {
  // Declare variables
  var input, filter, ul, li, a, i, txtValue;
  input = document.getElementById('myInput');
  filter = input.value.toUpperCase();
  ul = document.getElementById("myUL");
  li = ul.getElementsByTagName('li');
  // Traverse all list items and hide those that do not match the search query
  for (i = 0; i < li.length; i++) {
    a = li[i].getElementsByTagName("a")[0];
    txtValue = a.textContent || a.innerText;
    if (txtValue.toUpperCase().indexOf(filter) > -1) {
      li[i].style.display = "";
    } else {
      li[i].style.display = "none";
    }
  }
}
</script>

Try it yourself

Tip:If you need to perform a case-sensitive search, please remove toUpperCase().

Related Pages

Tutorial:How to Filter/Search Table