🧠 Make a Real-Time Search Filter for a List in JavaScript
Have you ever used a search bar on a website that instantly filters a list as you type? That's called a real-time search filter. In this article, we'll learn how to create this powerful feature using pure JavaScript — no libraries needed!
We’ll go step-by-step and explain everything in simple language so even a beginner can understand and build it.
🎯 What We Will Build
We’ll create:
-
A simple list of items (e.g., names of fruits)
-
A search input box
-
A real-time filter using JavaScript that hides non-matching items as you type
Here’s a preview of the final result:
When you type "ap", only Apple and Grapes will show. Cool, right?
🧱 Step 1: Create the HTML Structure
We’ll start with a basic HTML page that includes:
-
A search input
-
An unordered list (
<ul>
) with list items (<li>
)
💻 HTML Code:
🧠 Step 2: Add JavaScript to Filter the List
Now let’s add the JavaScript code that will:
-
Detect when the user types in the search box
-
Get the search value
-
Loop through each list item
-
Show only the items that match the search
💻 JavaScript Code (script.js
file):
🔍 Code Explanation
Let’s break down what’s happening step by step:
✅ Get Elements
-
We're grabbing the input box and list items using
getElementById
andgetElementsByTagName
.
✅ Add Event Listener
-
Every time the user types a key (
keyup
), the function runs.
✅ Convert Input to Lowercase
-
This makes the search case-insensitive (so "apple" matches "Apple").
✅ Loop Through Each List Item
-
We loop through all
<li>
elements and get their text.
✅ Show or Hide Items
-
If the list item includes the typed word, we show it.
-
Otherwise, we hide it using
display: none
.
✅ Bonus Tip: Add More Items or Categories
You can easily update this list to search for:
-
Names of countries
-
Movie titles
-
Products in a shop
-
Anything else!
Just replace the <li>
items in HTML with your own content.
🧪 Final Output
Here’s a quick demo of what it looks like in your browser:
📌 Conclusion
Congratulations! 🎉 You just built a real-time search filter using plain JavaScript. This small but powerful feature is very useful in websites, search tools, and applications.
What You Learned:
-
How to get elements in JavaScript
-
How to use event listeners
-
How to loop through list items
-
How to filter based on input
📁 Full Project Files
If you want to test it locally, create two files:
-
index.html – Copy the HTML code
-
script.js – Copy the JavaScript code
Then open index.html
in your browser and try typing in the input box!