Back to the lesson

Original working file

public/search.js

Code and working example pages keep their original identifiers and sample text. The lesson and file guidance explain them in your language.

const form = document.querySelector("form"),
  status = document.querySelector("[role=status]"),
  list = document.querySelector("#results");
let entries;
form.addEventListener("submit", async (e) => {
  e.preventDefault();
  list.replaceChildren();
  const query = form.elements.query.value.trim().toLowerCase();
  if (!query) {
    status.textContent = "Enter a topic to search for.";
    return;
  }
  status.textContent = "Searching…";
  try {
    if (!entries) {
      const r = await fetch("search-index.json");
      if (!r.ok) throw Error();
      const data = await r.json();
      if (
        !Array.isArray(data) ||
        data.some(
          (x) =>
            typeof x.title !== "string" ||
            typeof x.text !== "string" ||
            !/^blog\/[a-z0-9-]+\.html$/.test(x.url),
        )
      )
        throw Error();
      entries = data;
    }
    const words = query.split(/\s+/),
      matches = entries.filter((x) =>
        words.every((w) => (x.title + " " + x.text).toLowerCase().includes(w)),
      );
    for (const x of matches) {
      const li = document.createElement("li"),
        a = document.createElement("a");
      a.href = x.url;
      a.textContent = x.title;
      li.append(a);
      list.append(li);
    }
    status.textContent = matches.length
      ? matches.length + " matching article(s)."
      : "No matching articles. Try a different topic.";
  } catch {
    status.textContent = "Search is unavailable. Browse the article index below.";
  }
});