Hide a div when multiple classes are filtered using jQuery

I have several divs with the class .item. When the user clicks on the Classfilter submit button, all .item elements that also have at least one class from the dateClasses array (for example ['28.09.2015', '29.09.2015']) should be hidden.

To clarify, the elements with the green border should be hidden when the button is clicked.

Important: The values in the dateClasses array may change dynamically, and I need to check against an array.

$(document).ready(function() {
  classFilter();
});


function classFilter() {
  $('#filter').click(function(e) {
    e.preventDefault();

    var dateClasses = ['28.09.2015', '29.09.2015']; //Hide the item-div if one of these classes is applied

    $('.item').filter(function() {
      $(this).hasClasses(dateClasses)
    }).addClass('hide-event');
  });
}

$.fn.extend({
  hasClasses: function(selectors) {
    var self = this;
    for (var i in selectors) {
      console.log($(self).hasClass(selectors[i]));
      if ($(self).hasClass(selectors[i])) {
        return true;
      }
    }
    return false;
  }
});
.hide-event {
  display: none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="item 28.09.2015" style="border: 10px solid green">
  Hide this if class is in array</div>
<div class="item 29.09.2015" style="border: 10px solid green">
  Hide this if class is in array</div>
<div class="item 30.09.2015" style="border: 10px solid blue">
  Hide this if class is in array</div>
<input type="submit" name="filter" value="Classfilter" id="filter">

Answer №1

Remember: Avoid using dot in class names, and consider replacing them with characters like - or _ before inserting them into the DOM.

Your filter() function is not returning anything.

To correct the filter:

$('.item').filter(function() {
     return  $(this).hasClasses(dateClasses);
}).addClass('hide-event');

While there may be simpler solutions to achieve your goal, this snippet addresses the core issue without modifying your plugin.

A straightforward alternative could be:

$('.item').filter('.' + dateClasses.join(',.')).addClass('hide-event');

Check out a demo with valid class names here

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

The Vue conditional event handling with the v-on directive and the prevent modifier

Is there a way to utilize the .prevent modifier of v-on dynamically? <a href="#" class="modal-overlay" aria-label="Close" v-on="overlayClickClosesModal ? { click: () => closeModal() } : {}" /> I'm attempting to prevent the URL from ...

Experiencing trouble with implementing multiple textboxes based on option selection using javascript

My JavaScript code is supposed to display multiple textboxes based on the user's selection, but for some reason, I can only select one textbox at a time. I'm not sure what's wrong with my code. Here's the snippet of the code: <ht ...

Stripping CSS prefixes upon file initialization

When developing my application, I have a process in place where I load CSS files on the back-end using Express.JS and then transmit them to the front-end. However, before sending the CSS code to the front-end, I need to: Identify the user's browser; ...

A guide on using Beautiful Soup to retrieve all text elements from a specific class

This is my custom code snippet: # -*- coding: utf-8 -*- from time import sleep import requests from bs4 import BeautifulSoup def get_all_coins(): response = requests.get("https://coinmarketcap.com/") soup = BeautifulSoup(response.content, 'ht ...

How to Enhance GraphQL Mutation OutputFields with a Function Generator

I'm encountering issues while trying to incorporate a function generator within a GraphQL mutation. The function generator is utilized to streamline the promise chain inside the mutation. Prior to refactoring the code, everything was functioning corr ...

Here is a way to retrieve the name of a ref object stored in an array using Vue.js 3 and Typescript

I have a Form, with various fields that I want to get the value of using v-model and assign them to ref objects. In order to populate my FormData object with this data, I require both the name and the value of the ref objects. Unfortunately, I am struggli ...

The quantity of elements stays constant even after adding to them using Javascript

I have implemented a notes list feature that allows users to add notes using an input field. Beneath the notes list ul, there is a message showing the total number of notes: $('li').length. However, I encountered an issue where the count of not ...

What's the secret behind generating a crisp 400 on paper?

Understanding Why it Prints 400 I'm struggling to comprehend the logic behind this var x = {}, y = { key: "y" }, z = { key: "z" }; x[y] = 100; x[z] = 200; console.log(x[y] + x[z]); ...

show a picture and text side by side

Here's the CSS code I'm using: <style type="text/css"> #box { width:100%; height:80px; background-color:#eeeeee; } .box-inner { width:80%; margin:0 auto 0 auto; text-align:center; } #text, #text a { font-siz ...

Steps for building JSX with a loop

Recently diving into the world of React and Javascript, I've been attempting to assemble a JSX 'tree' dynamically using a loop rather than hard-coding the data. However, I find myself facing a hurdle where Visual Studio Code insists on havi ...

Displaying Hierarchical Data with AngularJS and ng-repeat

Recently, I've been working on finding an elegant solution to represent hierarchical data in my application. Specifically, I have implemented a slide effect for bootstrap badges that showcase sub-categories using AngularJS. With some guidance from th ...

Unsupported MIME format

I'm encountering an issue where my stylesheet is not applying to my handlebars. It was working fine yesterday, but today I'm seeing a MIME error and I'm unsure of the reason behind it. Any assistance would be greatly appreciated. Server Cod ...

discovering obscured information using jquery

I am working on a code snippet where I need to hide the detailed content for display purposes and only show it during printing: <div> <ul> <li> <span style="font-size: 1.25em;"> <strong> ...

Angular JS does not display the bold tag for specific words

I'm currently working on an Angular JS application and receiving text from the server that needs to be displayed on my website. The text received from the server is: "My name is <b> John </b>" with b tags. Unfortunately, when I display ...

Submitting form data triggers an AJAX request that retrieves and displays the desired content within a

When it comes to opening search results in a specific form on a webpage using Ajax, many developers may face certain challenges. Here is an example of how it can be implemented: <form id="searchForm" method="GET" > <INPUT TYPE="text" N ...

Methods for inserting text into a WebBrowser Document without retrieving any Attributes in vb.net

Is it possible to retrieve text from a WebBrowser Document in vb.net without retrieving any attributes?! For example: <h1>text here</h1> Or: <h1 name="anything">text here</h1> How can I extract the "text here" within the <h1 ...

Webix UI - Struggling to create dynamically responsive components during screen resizing

Can anyone guide me on how to make my Webix UI control responsive in the free version available at ? It seems to be acting unpredictably due to the AngularJS integration code I'm using. I have attempted various solutions like media queries, redraw, a ...

Manipulating the actual DOM in ReactJS to display a formatted number or string while preserving its original value

Hello, I am new to ReactJS and currently using it along with ReactDataGrid. I am trying to figure out how to change the real DOM value of a specific cell in the table. Here is the table I am working with: https://i.sstatic.net/CAcSH.png My goal is to cha ...

Personalize the color of tags in streamlit

As a newcomer to streamlit, I am experimenting with creating an application that incorporates multiple tag objects. By default, the tags are displayed in red, but I would like to customize the colors for each tag based on its category. For example, I want ...

Activating a certain class to prompt a drop-down action

My PHP code is displaying data from my database, but there's a bug where both dropdown menus appear when I click the gear icon. I want only one dropdown to appear when clicking the gear of a specific project. Can you help me fix this issue? It's ...