DEV Community

Arhan Khan
Arhan Khan

Posted on

Build a Search Filter with JavaScript

Every app you use has a search box. Building one teaches you the most useful front-end skill there is: take a list, take what the user typed, and show only what matches. It is twenty lines of code, and it appears in nearly every project you will ever build.

The plan

  1. A list of items rendered from an array.
  2. An input that filters the list as the user types.
  3. A "no results" message when nothing matches.
  4. Matching text highlighted in the results.

The HTML

<input id="search" type="text" placeholder="Search fruits...">
<ul id="list"></ul>
<p id="empty" hidden>No results found.</p>
Enter fullscreen mode Exit fullscreen mode

The JavaScript

const items = [
  'Apple', 'Banana', 'Mango', 'Orange', 'Pineapple',
  'Grapes', 'Papaya', 'Watermelon', 'Strawberry', 'Kiwi'
];

const list = document.getElementById('list');
const empty = document.getElementById('empty');

function highlight(text, query) {
  if (!query) return text;
  const index = text.toLowerCase().indexOf(query.toLowerCase());
  if (index === -1) return text;
  return text.slice(0, index) +
    '<mark>' + text.slice(index, index + query.length) + '</mark>' +
    text.slice(index + query.length);
}

function render(query = '') {
  const q = query.trim().toLowerCase();
  const shown = items.filter(item => item.toLowerCase().includes(q));
  list.innerHTML = shown.map(item =>
    `<li>${highlight(item, q)}</li>`
  ).join('');
  empty.hidden = shown.length !== 0;
}

document.getElementById('search').addEventListener('input', (e) => {
  render(e.target.value);
});

render();
Enter fullscreen mode Exit fullscreen mode

Three details beginners miss

  • Filter on lowercase, display the original. Comparing toLowerCase() on both sides makes "mango" match "Mango", while the displayed text keeps its proper capital.
  • Debounce for big lists. For ten items it does not matter. For ten thousand, filter on every keystroke and the page stutters. Wait 200ms after the last keystroke before filtering:
let timer;
input.addEventListener('input', (e) => {
  clearTimeout(timer);
  timer = setTimeout(() => render(e.target.value), 200);
});
Enter fullscreen mode Exit fullscreen mode
  • Always handle zero results. A blank list looks broken. A "No results found" message looks intentional — and it tells the user to try a different word.

What to add next

Filter by category as well as text, sort the results, search across multiple fields (name and description), and fetch the list from an API instead of a hard-coded array.

Top comments (0)