3 Steps To Filter/Search a List in Javascript (Simple Examples)

Welcome to a beginner’s tutorial on how to filter or search a list in Javascript. So you have a long list of products, users, inventory… or just about any item for the matter. How do we improve the interface and add a search filter to that massive list?

Yep, that is doing a search using client-side Javascript, and not throwing the search request back to the server. Save the server’s resources, and use the users’ devices. Thankfully, it really isn’t that difficult. Read on to find out how!

ⓘ I have included a zip file with all the example source code at the start of this tutorial, so you don’t have to copy-paste everything… Or if you just want to dive straight in.

 

 

QUICK SLIDES

 

TABLE OF CONTENTS

Download & Demo Filter List AJAX Filter
Useful Bits & Links The End

 

DOWNLOAD & NOTES

Firstly, here is the download link to the example code as promised.

 

QUICK NOTES

If you spot a bug, feel free to comment below. I try to answer short questions too, but it is one person versus the entire world… If you need answers urgently, please check out my list of websites to get help with programming.

 

EXAMPLE CODE DOWNLOAD

Click here to download the source code, I have released it under the MIT license, so feel free to build on top of it or use it in your own project.

 

 

LIST FILTER DEMO

  • Apple
  • Apricots
  • Avocado
  • Banana
  • Blackberries
  • Blueberries
  • Cherries
  • Coconut
  • Cranberries
  • Durian
  • Elderberries
  • Grapefruit
  • Grapes
  • Guava
  • Honeydew
  • Jackfruit
  • Longan
  • Loquat
  • Mango
  • Orange
  • Papaya
  • Pear
  • Pineapple
  • Strawberries
  • Watermelon

 

FILTER LIST

All right, let us get started with creating a simple HTML list and adding a Javascript search box to it.

 

STEP 1) THE HTML

1-page.html
<!-- (A) SEARCH BOX -->
<input type="text" id="the-filter" placeholder="Search For..."/>
 
<!-- (B) LIST OF ITEMS -->
<ul id="the-list">
  <li>Apple</li>
  <li>Apricots</li>
  <li>Avocado</li>
  <li>Banana</li>
  <li>Blackberries</li>
  <li>Blueberries</li>
  <li>Cherries</li>
  <li>Coconut</li>
  <li>Cranberries</li>
  <li>Durian</li>
  <li>Elderberries</li>
  <li>Grapefruit</li>
  <li>Grapes</li>
  <li>Guava</li>
  <li>Honeydew</li>
  <li>Jackfruit</li>
  <li>Longan</li>
  <li>Loquat</li>
  <li>Mango</li>
  <li>Orange</li>
  <li>Papaya</li>
  <li>Pear</li>
  <li>Pineapple</li>
  <li>Strawberries</li>
  <li>Watermelon</li>
</ul>

The HTML is very straightforward, and there are only 2 parts to it:

  • <input type="text" id="the-filter"/> The search box.
  • <ul id="the-list"> List of items.

 

 

STEP 2) THE CSS

2-theme.css
/* (A) SEARCH BOX */
#the-filter {
  box-sizing: border-box;
  width: 100%;
  margin-bottom: 15px;
  padding: 10px;
}
 
/* (B) LIST */
#the-list {
  list-style: none;
  margin: 0;
  padding: 0;
}
#the-list li {
  padding: 10px;
  border-bottom: 2px solid #ffe9e9;
}
#the-list li:hover { background: #fffed6; }
#the-list li.hide { display: none; }

These are just some cosmetics, basically styling the unordered list #the-list to look nicer with stripes and stuff. The only thing to take note of is the #the-list li.hide class – We will use this one to hide list items that don’t match the search term later.

 

STEP 3) THE JAVASCRIPT

3-filter-list.js
window.addEventListener("load", () => {
  // (A) GET HTML ELEMENTS
  var filter = document.getElementById("the-filter"), // search box
      list = document.querySelectorAll("#the-list li"); // all list items
 
  // (B) ATTACH KEY UP LISTENER TO SEARCH BOX
  filter.onkeyup = () => {
    // (B1) GET CURRENT SEARCH TERM
    let search = filter.value.toLowerCase();
 
    // (B2) LOOP THROUGH LIST ITEMS - ONLY SHOW THOSE THAT MATCH SEARCH
    for (let i of list) {
      let item = i.innerHTML.toLowerCase();
      if (item.indexOf(search) == -1) { i.classList.add("hide"); }
      else { i.classList.remove("hide"); }
    }
  };
});

Sorry to the folks who are expecting to see hundreds of lines of code… Because this is all we need. This should be very straightforward as well, just follow through step-by-step:

  • (A) Wait for the page to be fully loaded first, then get the HTML search box and all the list items.
  • (B) Attach an onkeyup listener to the search box, this will be fired whenever the user presses a key in the search box.
  • (B1 & B2) Get the current search term, then loop through all the list items. Hide the items that don’t match the search term using the .hide CSS class, show the items that match by removing the .hide CSS class.

The end. If you want a case-sensitive search, remove both .toLowerCase() from the script.

 

 

AJAX FILTER LIST

What if we want to use AJAX to fetch raw data from the server? How do we generate a list and attach a filter to it? Here is a small modification to the above example.

 

STEP 1) HTML PAGE

e1-page.html
<!-- (A) SEARCH BOX -->
<input type="text" id="the-filter" placeholder="Search For..."/>

<!-- (B) LIST OF ITEMS -->
<ul id="the-list"></ul>

Yep, it’s the same as above, except that the list of items is empty now – We will load it via AJAX instead.

 

STEP 2) SERVER-SIDE DATA

e2-server.json
["Apple","Apricots","Avocado","Basnana","Blackberries","Blueberries","Cherries","Coconut",
"Cranberries","Durian","Elderberries","Grapefruit","Grapes","Guava","Honeydew","Jackfruit",
"Longan","Loquat","Mango","Orange","Papaya","Pear","Pineapple","Strawberries","Watermelon"]

This is the part where you generate the list of items on the server side. That could be extracting data from the database, reading from a file, or getting raw data from somewhere else… Not going into the details here since it is different for everyone. I am just going to leave this simple list of JSON-encoded fruits as an example.

 

 

STEP 3) JAVASCRIPT

e3-filter-list.js
window.addEventListener("load", () => {
  // (A) GET DATA FROM SERVER VIA AJAX FETCH
  fetch("e2-server.json")
  .then((res) => res.json())
  .then((data) => {
    // (B) GET HTML ELEMENTS
    let filter = document.getElementById("the-filter"), // search box
        list = document.getElementById("the-list"); // list item wrapper
 
    // (C) DRAW HTML LIST
    for (let i of data) {
      let li = document.createElement("li");
      li.innerHTML = i;
      list.appendChild(li);
    }
 
    // (D) SAME AS BEFORE
    list = document.querySelectorAll("#the-list li");
    filter.onkeyup = () => {
      // (D1) GET CURRENT SEARCH TERM
      let search = filter.value.toLowerCase();
 
      // (D2) LOOP THROUGH LIST ITEMS - ONLY SHOW THOSE THAT MATCH SEARCH
      for (let i of list) {
        let item = i.innerHTML.toLowerCase();
        if (item.indexOf(search) == -1) { i.classList.add("hide"); }
        else { i.classList.remove("hide"); }
      }
    };
  });
});

The Javascript remains pretty much the same as well.

  1. Load the data from the server using fetch().
  2. Looks familiar? Same – We get the search box and empty list.
  3. Generate the list items from the data.
  4. Get all the generated list items, this part is entirely the same as above.

 

USEFUL BITS & LINKS

That’s all for this tutorial, and here is a small section on some extras and links that may be useful to you.

 

LINKS & REFERENCES

 

COMPATIBILITY CHECKS

This search filter will work on all modern browsers.

 

YOUTUBE TUTORIAL

 

INFOGRAPHIC CHEAT SHEET

How To Search/Filter a List In Javascript (Click To Enlarge)

 

THE END

Thank you for reading, and we have come to the end of this guide. I hope that it has helped you with your project, and if you want to share anything with this guide, please feel free to comment below. Good luck and happy coding!

5 thoughts on “3 Steps To Filter/Search a List in Javascript (Simple Examples)”

    1. 1) Start with an empty <ul>
      2) Define the data in a Javascript array instead.
      3) Modify the Javascript to append <li> into the empty list for the matched results.

  1. This was exactly what I needed. We had a list of veterans that was provided in a plain “ format, and this solution was easy to integrate without any need for list conversion.

    Much appreciated, and great work!

  2. Hello Toh,
    I walked through your project “3 Simple Steps To Filter/Search a List in Javascript”, it is really nice, appreciated.
    I am passing very hard time to figure how to go for wild search in search box from a selected field in combo box which I covered in VB DotNet.
    The scenario is
    a) The random search records display in Listbox, then click/select the specific record, will display in respective input/text boxes for further edit the selected record.
    In PHP, things are little different. What’s your suggestion? Can you refer for good project/example/s, so that I can come up with some reasonable solution for my problem?
    How I can send the screen shot of my project? Then you could be able to get the good idea.

    Thanks .
    Regards.
    Shamsul Arifin

Leave a Comment

Your email address will not be published.