Is there an efficient way to quickly verify if a large number of elements have a specific class using a query parameter or string

My goal is to create a filtering feature where users can choose from categories "a", "b", "c", "d", and "e". Users can come to the page with a specific query string like http://example.com?cate=a, http://example.com?cate=b, etc. The categories sorting buttons are presented as a group of radio buttons.

Below is the code snippet to activate the category sorting buttons:

function GetURLParameter(sParam) {
        var sPageURL = window.location.search.substring(1);
        var sURLVariables = sPageURL.split("&");
        for (var i = 0; i < sURLVariables.length; i++) {
            var sParameterName = sURLVariables[i].split("=");
            if (sParameterName[0] == sParam) {
                return sParameterName[1];
            }
        }
    }
    var cate = GetURLParameter("cate");

    switch (cate) {
        case "a":
            $(window).load(function() {
                $("#aBtn").prop("checked", true);
            });
            break;
        case "b":
            $(window).load(function() {
                $("#bBtn").prop("checked", true);
            });
            break;
        case "c":
            $(window).load(function() {
                $("#cBtn").prop("checked", true);
            });
            break;
        case "d":
            $(window).load(function() {
                $("#dBtn").prop("checked", true);
            });
            break;
        case "e":
            $(window).load(function() {
                $("#eBtn").prop("checked", true);
            });
            break;
        default:
            break;
    }

Next, I want to filter objects that match or do not match the selected categories "a", "b", "c", "d", and "e". Some objects may belong to more than one category. All objects have a common class called ".all". When filtering is active, objects that do not belong to the selected category must be assigned the class ".none".

Here is an example:

<div class="all a e">I have properties of both a and e.</div><!-- should display if query string includes a or e -->
<div class="all b e">I possess characteristics of both b and e.</div><!-- should display if query string includes b or e -->
<div class="all b c e">I contain attributes of b, c, and e.</div><!-- should display if query string includes b, c, or e -->
<div class="all c">I represent c alone.</div><!-- should display if query string includes c -->
<div class="all d">I signify d only.</div><!-- should display if query string includes d -->
<div class="all d">I also denote d.</div><!-- should display if query string includes d -->
<div class="all d e">I exhibit qualities of both d and e.</div><!-- should display if query string includes d or e -->

Should I consider adding a unique id for each object?

Answer №1

To easily manage them, consider using the hide() function to hide them all first and then reveal only the ones that match.

$(".all").hide();
$("."+cate).show();

If you want to include the class none:

$(".all").addClass("none");
$("."+cate).removeClass("none");

I've created a demonstration on CodePen where I demonstrate how the value of cate can be simulated using a text input.
;)

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

Scraping the web with Python: Selenium HTML elements may differ from what is shown in the inspect tool

In my current academic project, I am facing an issue with scraping news articles from websites. The problem arises when parsing HTML code in Python because the code obtained from the page source is different from what is shown in the Inspect Element tool. ...

Mistakes in serializing arrays for javascript in an ajax request

I am trying to send an array of JavaScript objects in an Ajax call. This is how I create my array: var itemsToEdit = []; $(".editedItem[value='true']").closest("tr").each(function() { var itemToEdit = { id: $(this).find(".i ...

the ajax post method

I recently wrote some code that involves two files (index.html and jeu.php). In the index.html file, when I submit a form, I am supposed to be redirected to the other page (jeu.php). However, the issue seems to be with the click event. <html> <he ...

Next.js app experiencing issues with Chakra UI not transitioning to dark mode

After attempting to incorporate Chakra UI into my Next.js application, I carefully followed every step outlined in their documentation: Despite setting the initialColorMode to "dark" for the ColorModeScript prop, it seems that the dark mode is not being a ...

What could be causing this getJSON call to return undefined?

On our internal server, we have a JSON service that returns a specific record structure as shown below: { "getLTCWithIDsResult": { "AIMSubmissionID": "", "BrokerName": "", "DateApplied": "/Date(1389302726241-0600)/", ...

Transmitting OfficeJS 2D Array via an Ajax Call

Struggling with sending a "large" table using OfficeJS: functionfile.html loaded from manifest route <script> (function (){ "use strict"; Office.initialize = function (reason) { $(document).ready(function() { $("#send-data-button").cli ...

Is it possible to input a Django template variable within an HTML code in a model's TextField field?

I am looking to dynamically generate external URLs rather than hard-coding them in HTML to accommodate any future changes. Within my template, I have the following code snippet. <p> {{ article.text|safe }} </p> Here is my Article class defin ...

Cross-site communication with Ajax using both POST and GET requests

As a beginner in JavaScript, I'm facing challenges with implementing ajax POST and GET requests. While I can successfully do it using Google Postman as shown here https://i.sstatic.net/Cegxj.pnghttps://i.sstatic.net/ovJT0.png, the problem arises when ...

Using JavaScript to make an AJAX call to a different domain while bypassing the Content Security Policy restrictions

While parsing a web page, I need to initiate an AJAX call to my localhost depending on the content. The purpose is to exchange data using a PHP script on my localhost, possibly in JSON format (still under testing). This process is part of a plugin that I ...

What is the most efficient method for linking the hostname of my website to the file path within my Express.js static file server?

When using vanilla JavaScript in the browser, we can retrieve the hostname using: window.location.hostname However, if we are working with Node.js/Express.js on the server side, how can we achieve the same result? Furthermore, I am looking for a way to ...

Error encountered when utilizing a testing client within Node.js

When checking the response in my client, I have implemented the following code: assert.strictEqual(data,{'status':'ok','message':'tweet received'}); The code used to send the message is as follows: res.send({sta ...

Slider with jQuery UI that has its midpoint set at 0 and its background extending out from that point

I'm looking to create a slider that ranges from -5 to 5 with the center at 0. The background color will change based on the position on the slider. Currently, I've only been able to achieve this using two sliders here: http://jsfiddle.net/ur4SH/ ...

Executing a post request asynchronously and storing the retrieved data into a variable

Currently, I am in the process of learning AngularJS and attempting to upgrade my current method of fetching data from a web service and dynamically assigning it to a variable that is binded using ng-repeat. My main objective is to implement an asynchronou ...

When the horizontal scroll is turned off, it also disables the functionality of my mobile-friendly

I came across a helpful post on StackOverflow that suggested using the following code to disable horizontal scrolling: html, body { overflow-x: hidden; } This solution did resolve my issue of horizontal scrolling, but unfortunately it caused problems ...

Ways to retrieve the output parameter in the node mssql

` request.input('xyz',sql.Int,1); request.input('abc',sql.Numeric,2); request.output('pqr',sql.Int); request.output('def',sql.Char); request.execute('[StoredProcedure]',function(err,recor ...

How can I make col-8 and col-4 display next to each other?

Here is the code snippet I recently submitted: <section class="main-container"> <div class="grid-row no-gutters"> <div class="column-8"> <img class="full-width-img& ...

How to retrieve JSON data in Angular.js

I'm having trouble accessing a json file in angular.js with the code below. I keep getting an error message and could really use some help! Here is my module : angular.module("demoApp", ['demoApp.factory','demoApp.controllers']); ...

Passing dynamic scope from Angular to a directive is a seamless process

I am working with a directive that retrieves an attribute value from an http call in the following manner: Controller app.controller("HomeController", function($scope){ $http.get("/api/source").then(function(res){ $scope.info = res.data }); }); ...

Use JavaScript to send GET parameters to the server without needing to refresh the page

My goal is to execute a GET request in JavaScript when a download link is clicked. Upon clicking the link, a GET request should be sent to a PHP script that tracks the number of times the link is clicked. Although I'm relatively new to JavaScript, I h ...

Minimize the number of axios requests made every time a Vue component is displayed

I am relatively new to Vue, so please bear with me as I may not have all the knowledge in this area. Within one of my child components (Product_Collection.vue), I am making an axios request to retrieve products from my Shopify store using their GraphQL ...