How to Create a Working Search Bar Using HTML and JavaScript?

Estimated read time 3 min read

You can create a working search bar using HTML and JavaScript by creating an input field for the user to type in the search query, and then using JavaScript to filter the data based on the user’s input. Here’s an example:

<input id="search" type="text" placeholder="Search...">
<table id="data-table">
    <td>John Doe</td>
    <td>New York</td>
    <td>Jane Doe</td>
    <td>Jim Brown</td>
const searchInput = document.querySelector("#search");
const table = document.querySelector("#data-table");

searchInput.addEventListener("input", (event) => {
  const searchTerm =;
  const rows = table.querySelectorAll("tr");
  rows.forEach((row) => {
    const cells = row.querySelectorAll("td");
    let match = false;
    cells.forEach((cell) => {
      if (cell.textContent.toLowerCase().includes(searchTerm)) {
        match = true;
    if (match) { = "";
    } else { = "none";

In this example, we have an input field with the id attribute set to “search”, and a table with the id attribute set to “data-table”. We use the querySelector method to select the search input and table elements, and add an event listener to the search input that listens for changes to the input value. Whenever the input value changes, we convert the value to lower case and store it in the searchTerm variable. We then use the querySelectorAll method to select all the rows in the table, and for each row, we use querySelectorAll again to select all the cells in the row. We then iterate over the cells, and for each cell, we check if its text content, converted to lower case, includes the search term. If it does, we set the match variable to true and break out of the loop. After looping over all the cells, if the match variable is true, we set the display style of the row to an empty string, otherwise, we set it to “none”. This will show or hide the rows in the table based on whether their cell values match the search term.

You May Also Like

More From Author

+ There are no comments

Add yours

Leave a Reply