Select Page

I hope this code will help you get to what you need or atleast take you near to it. I created it to search text inside cards where user writes some text in input tag and the results is displayed by hiding all those who does not have that string. This script can perform basic search upto any level inside the card (main element that you want to hide or show). You just need to add class searchable to that element.

Here is the Demo and code for the same. You will need to include jQuery for this to work.


Demo

See the Pen jQuery search text inside div to any level and add a class to parent element by Puneet Sharma (@webdevpuneet) on CodePen.

HTML

<input id="filterCards" class="search" type="text" placeholder="Search text here..."></input>

<div class="cards">
  <div class="card">
    <h2 class="searchable">Title One</h2>
    <p class="searchable">paragraph one</p>
  </div>
  
  <div class="card">
    <h2 class="searchable">Title Two</h2>
    <p class="searchable">paragraph two</p>
  </div>
  
  <div class="card">
    <h2 class="searchable">Title Three</h2>
    <p class="searchable">paragraph three</p>
  </div>
  
  <div class="card">
    <h2 class="searchable">Title Four</h2>
    <p class="searchable">paragraph four</p>
  </div>
</div>

<a class="reference" href="">Full Article</a>

CSS

body{
  padding:50px;
}
.cards{
  border:1px solid #cecece;
  padding:20px;
  border-radius:5px;
  font-size:16px;
}
.card{
  width:200px;
  height:200px;
  display:inline-block;
  border:1px solid #cecece;
  margin-right:20px;
  background:#fafafa;
  border-radius:5px;
  padding:20px;
  text-align:center;
}
.search{
  border:1px solid #cecece;
  margin-bottom:20px;
  height:40px;
  width:250px;
  border-radius: 5px;
  padding-left:10px;
}
.reference{
  margin-top:20px;
  display:inline-block;
}

jQuery

include jQuery before this script –

<script type='text/javascript' src='https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js'></script>

<script>
// Search and sort cards
$(document).ready(function () {
  $("#filterCards").keyup(function () {
    var filter = $(this).val();
    $(".card").each(function () {
      var $i = 0;
      $(this)
        .find(".searchable")
        .each(function () {
          if ($(this).text().search(new RegExp(filter, "i")) >= 0) {
            $i++;
          }
        });
      if ($i > 0) {
        $(this).closest(".card").show();
      } else {
        $(this).closest(".card").hide();
      }
    });
  });
});
</script>