DEV Community

Cover image for Simple Search box using JavaScript
Harshita Nahta
Harshita Nahta

Posted on


Simple Search box using JavaScript

Simple search operation using JavaScript to filter out the items from list.

so we have a search box here and an unordered list with 0 child items.

<div class="center">
<textarea rows="1" name="searchBox" id="searchBox" placeholder="Type to search"></textarea>
<i class="material-icons">search</i>
<ul class="center" id="list">

Enter fullscreen mode Exit fullscreen mode
  • add elements to the list using DOM Manipulation
var list= ["banana" , "strawberry" , "orange" , "apple"]

var listEle = document.getElementById("list");

insertListItems = (tempList) => {
   listEle.innerHTML = "";>{
      var liEle = document.createElement("LI");
      var liText = document.createTextNode(i);          


Enter fullscreen mode Exit fullscreen mode

now add onkeyup event in textarea to call the search function on entering any value in textarea

<textarea onkeyup="search(this.value)"  placeholder=" type to search" rows="1" name="searchBox" id="searchBox"></textarea>

Enter fullscreen mode Exit fullscreen mode

the function takes search value as parameter and checks if the search value is not empty if it is empty it simply uses the same data , else using the filter method we can filter out values accordingly

Note : toUpperCase method is used so that search results are not case sensitive.

search = (searchTerm) => {
  searchTerm = searchTerm.toUpperCase()
  var temp = list;
  if(searchTerm != ""){
      listEle.innerHTML = "";
      temp = list.filter((i)=>{
        i = i.toUpperCase()
        if( i.indexOf(searchTerm) != -1){
           return i

Enter fullscreen mode Exit fullscreen mode

Link for reference :-

Happy Developing!

Top comments (2)

lukeshiru profile image
Luke Shiru

A few issues with this:

  1. You should use an input with type search instead of a textarea.
  2. You don't need JS, you can use a datalist instead.
  3. The icon ideally should have role="img" so the screen readers omit it.

This issues are mainly related to a11y and UX in general (with type search the UX is better in mobile, for example).

Here's a snippet with an example:

<input list="search-results" type="search" placeholder="Type to search" />

<datalist id="search-results">
    <option value="banana"></option>
    <option value="strawberry"></option>
    <option value="orange"></option>
    <option value="apple"></option>
Enter fullscreen mode Exit fullscreen mode


harshitanahta profile image
Harshita Nahta

Thanks for taking a look and sharing your feedback!