Skip to main content

Searching / Filtering Using Javascript And CSS3 Trick

By April 29, 2017Blog, CSS, CSS3, Javascript, Vanilla
Allure Web Solutions Code Snippet

How to implement a simple CSS based search using only JavaScript. There aren’t many use cases for this functionality, but if it matches what you’re trying to accomplish, it’s blazing fast and lean. There are some limitations which include only being able to search for what appears in the data-index attribute.


See the Pen Search / Filtering Using Javascript And CSS3 Trick by Mike Doubintchik (@allurewebsolutions) on CodePen.


 <!-- Search box -->
    <input type="text" placeholder="Search" id="search">

    <!-- Search results displayed inside these style tags !-->
    <style id="search-results"></style>
    <!-- Sample data -->
        <th>First Name</th>
        <th>Last Name</th>
      <tr class="searchable" data-index="jon snow">
      <tr class="searchable" data-index="james bond">
      <tr class="searchable" data-index="shawn the sheep">
        <td>The Sheep</td>
      <tr class="searchable" data-index="yo yo ma">
        <td>Yo Yo</td>

The JavaScript

// define variable
var searchResults = document.getElementById("search-results");
var searchBox = document.getElementById("search");

// add even listener to the search box
searchBox.addEventListener("input", function() {
  // if no results found, search results are empty
  if (!this.value) {
    searchResults.innerHTML = "No results";

  // if characters typed in search box don't match any data-index, hide with display: none
  searchResults.innerHTML =
    '.searchable:not([data-index*="' +
    this.value.toLowerCase() +
    '"]) { display: none; }';

// Credits:

Author allure

More posts by allure

Leave a Reply

Designed by

best down free | web phu nu so | toc dep 2017