Guide to setting up a search function with class name filtering

I am currently managing a website with multiple items, each represented by individual div elements. While all items share one common class name, they also have several other class names serving as tags to differentiate them (some tags may overlap between different items).

On the website, I have buttons set up using data-filter=".exampleclass" and data-filter=".exampleclass2", which effectively sort the items based on their class names. Now, I am exploring the idea of implementing a search bar where users can input a class name directly, eliminating the need for separate sorting buttons.

document.getElementById("boxsearch").oninput = function() {
  var matcher = new RegExp(document.getElementById("boxsearch").value, "gi");
  for (var i = 0; i < document.getElementsByClassName("portfolio-item").length; i++) {
    if (matcher.test(document.getElementsByClassName("category")[i])) {
      document.getElementsByClassName("portfolio-item")[i].style.display = "inline-block";
    } else {
      document.getElementsByClassName("portfolio-item")[i].style.display = "none";
    }
  }
}

Click here for an example in JSFiddle

Currently, I do not have the jQuery file included, so the buttons are not functioning properly. However, they work fine on my end. I just need guidance on how to enable the search functionality to filter items by their class names.

While researching, I found a similar concept that aligns with my goals: View the example here

Answer №1

Filtering elements based on regular expression matches with one of their class names can be inefficient. It is recommended to build an index and utilize a more optimized search algorithm for filtering elements.

An alternative approach involves using a single class to select the desired elements, iterating over them, accessing their classList, and then searching for matches. However, this method may inadvertently test other unrelated class names for filtering or sorting purposes.

A more effective solution could be to incorporate filter and sorting values as data- attributes to distinguish them from other factors. Additionally, creating an index of target elements allows for efficient retrieval and manipulation of specific elements.

Repeated calls to getElementByClassName can be costly and redundant, especially within a loop. The provided example demonstrates calling this function multiple times per keyup event.

function filterOnClass(baseClass, s) {
  let re = new RegExp(s.trim(), 'i');
  document.querySelectorAll('.' + baseClass).forEach(node => {
    let cNames = Array.from(node.classList);
    // Show all if search string is blank
    if (s.trim() == '') {
      node.classList.remove('hide');
    // Otherwise, filter 
    } else if (cNames.some(cName => re.test(cName))) {
        node.classList.add('hide');
    } else {
      node.classList.remove('hide');
    }
  });  
}
.box {
  height: 50px;
  width: 100px;
  border: 1px solid blue;
}

.hide {
  display: none;
}
<input id="searchInput" onkeyup="filterOnClass('box', this.value)"><br>
<div class="box foo">foo</div>
<div class="box foo bar">foo bar</div>
<div class="box fum bar">fum bar</div>
<div class="box fum">fum</div>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Issues with displaying form/button glyphicon when using a fixed table header in Bootstrap

I have a situation where I have a table with a fixed header. In one of the columns, there are delete buttons within a form. The table structure is as follows: <div class="panel panel-default table-responsive fixedHeader"> <!-- Table --> &l ...

What steps can be taken to troubleshoot an AJAX error that does not display any error messages?

Within my ajax code, I have the following: $(document).ready(function(){ $("form input#dodaj").click(function(){ var s = $("form input#zad").val(); var str = "<li>"+s+"</li>"; $.ajax( { type: "GET", ...

What is the best way to call upon a necessary module from various files?

When working with Node.js, I am using Socket.io in my main.js file like this: const io = require('socket.io')(http); Additionally, I have a separate "sub" file called api.js where I delegate some of my business logic. To include this file, I us ...

Executing Cross-Component Communication in Angular 7: A Quick Guide

I've encountered a challenge with a checkbox in the header component. If the checkbox is checked, I need to display an alert message when the application loads. The tricky part is that the checkbox is linked to the home component. Therefore, if I am o ...

What is the best way to simulate DynamoDB promise functionality with Jest?

Looking for a solution without using any libraries (as they haven't worked in my case). How can I make it work for that promise returned by the dynamodb query? Check out the code to be tested below: const isUrl = require('is-url'); const ...

Exploring the dynamic duo of Django and DataTables: a guide on incorporating

Have you cautiously attempted to fetch data using AJAX, and displaying it in a datatable works seamlessly, but the issue arises when attempting to search or sort within the table. It seems that upon doing so, the data is lost, necessitating a page reload. ...

Tips for adjusting the dimensions of my chart using JavaScript or Jquery

Utilizing DevExtreme widgets for the creation of a line chart in jQuery as shown below: var dataSource = [{"Date Range": "August-2018", Benelux: 194, Czech_Slovakia: 128, ...

Encountering difficulties accessing props while invoking a component in React

In my project, I've created a component called FilterSliders using Material UI. Within this component, I passed a prop named {classes.title} by destructuring the props with const { classes }: any = this.props;. However, when I try to access this prop ...

Guide to altering JSON using Javascript

https://github.com/smelukov/loftschool-example i am currently working on my project in this environment. I have created a friends.json file in the main folder. friends.json { "name": "John", "lastName": & ...

:after pseudo class not functioning properly when included in stylesheet and imported into React

I am currently utilizing style-loader and css-loader for importing stylesheets in a react project: require('../css/gallery/style.css'); Everything in the stylesheet is working smoothly, except for one specific rule: .grid::after { content: ...

"Using a triangular background shape in JavaScript instead of a traditional circular

I want to add a unique effect to my site inspired by the AnimatedHeaderBackgrounds demo available at this link. My twist on this effect involves using upward-moving triangles instead of circles. I've explored various resources, including Stack Overfl ...

Rearranging the order of Div elements within a main container using JavaScript DOM manipulation

How can I move elements within a div from the start to the end in the same div, for example, changing the order from 1-2-3 to 2-3-1? My code: const cards = document.querySelectorAll(".card"); const firstCard = document.querySelectorAll(".card")[0].inne ...

Creating a Modal in React without the need for a button to trigger it

I am working on implementing a model using the React Material UI library to display information on the landing page when a user logs in. However, I am facing an issue with closing the modal once it appears despite using a timeout trigger. const[post,setP ...

Unable to cancel $interval within factory

I created a factory for long-polling, complete with start and stop methods. However, I am struggling to cancel the timer. Any suggestions or ideas? app.controller("AuthCtrl", function($scope, $http, $window, User, Poller) { Poller.start(1, $scope.sess ...

Refresh cloned element after making changes to the original element

Just starting to explore Jquery and looking for some guidance to get me started :) Question: I'm facing an issue with a cart total price that is displayed in a different part of the page using clone(). I want this cloned price to automatically update ...

Google Maps and certain styles may require the browser to be refreshed multiple times

Something strange is happening with the Google Maps implementation on my website. Occasionally, when I first load the page, the map doesn't show up but appears after a refresh. Sometimes, I have to refresh multiple times before it displays properly. A ...

Retrieve the current element's 'this' object even after binding an external 'this' object

Is the title of this question confusing? Let's dive in. Imagine you have something like this: var Test = function(){ this.foo = a; } Test.prototype.init = function() { $(document).on('change', '.form-control', this.myFun ...

One controller, divergent template, introducing a fresh variable

I have a webpage where I showcase data (www.mysite.com/:gameId). In order to create a printer-friendly version of this data, I've set up a print page at www.mysite.com/:gameId/print. Both pages display the same information but with different designs. ...

What is the method for checking the pathname condition?

Hello, I am attempting to create an if statement for the pathname, but I am having trouble getting it to work properly. if (pathname == "/") { category = 'home'; pagetype = 'homepage'; } If the pathname matches "/", the script ...

Refreshing a PNG file without the need to refresh the entire page

Developed a captcha using imagestring imagestring($image, 5, 5, 30, $text, $text_color); imagepng($image,"captcha_image.png"); imagepng($image,"captcha_image.png"); The code snippet above shows part of the implementation. <img ...