LearnFrenzy
Sign in Take a free test

DOM Manipulation · DOM Coding Problems · Question 4

Live search that filters a list in JavaScript Solution, output & explanation

  • Program
  • Medium
  • 0 comments
  • Answer explained
  • Moderated community
Question 4 Back to Exercise

The page contains this HTML:

<input id="search" placeholder="Search topics"><ul id="topics"><li>Closures</li><li>Promises</li><li>Prototypes</li><li>Event Loop</li></ul><p id="count"></p>

As the user types in #search, hide the topics that do not contain the text (case-insensitive) using the hidden property, and show "N of 4 topics" in #count.

Solution
main.js
const search = document.getElementById("search");
const items = [...document.querySelectorAll("#topics li")];
const count = document.getElementById("count");

search.addEventListener("input", () => {
  const term = search.value.trim().toLowerCase();
  let shown = 0;
  for (const li of items) {
    li.hidden = !li.textContent.toLowerCase().includes(term);
    if (!li.hidden) shown++;
  }
  count.textContent = `${shown} of ${items.length} topics`;
});

for (const typed of ["pro", "P", "loop", ""]) {
  search.value = typed;
  search.dispatchEvent(new Event("input"));
  const visible = items.filter((li) => !li.hidden).map((li) => li.textContent);
  console.log(`"${typed}" → ${count.textContent}: ${visible.join(", ")}`);
}

Output Verified by running it on Node.js

"pro" → 2 of 4 topics: Promises, Prototypes
"P" → 3 of 4 topics: Promises, Prototypes, Event Loop
"loop" → 1 of 4 topics: Event Loop
"" → 4 of 4 topics: Closures, Promises, Prototypes, Event Loop

The input event fires on every change. Toggling the hidden property keeps the elements (and their listeners) in place; "P" also matches the p in "Loop".

Discussion & Comments 0

Share your method, a shortcut, or ask about a step you didn't follow.

No comments yet. Be the first to share your solution!

Post your comment

Comments appear after a quick review by our team.

Search LearnFrenzy

Esc

Quick links