Utilizing jQuery to toggle between adding and removing CSS classes for element identification

Below is a JavaScript/jQuery function that I have:

    function hideShowHiddens(action){
        $('.hidden_col').each(function(){
            if(action == 'show'){
                this.removeClass("hidden");
            }else{
                this.addClass("hidden");
            }
        });
    }

This function is supposed to search a JSP for every element with the CSS class '.hidden_col'. Depending on the parameter passed, it will add or remove another CSS class called '.hidden', which actually hides the elements.

Using this method should help me save around 400 lines of slow JavaScript functions, given the amount of data I am working with. However, when running it, I encounter an error from the browser indicating that this method is not supported. Can anyone explain why it's not working or provide a solution?

Answer №1

.addClass() and .removeClass() are two jQuery functions that allow you to manipulate classes on DOM objects. Using jQuery objects, which are enhanced versions of standard DOM objects, these functions can be applied after wrapping the DOM object in a jQuery wrapper.

function hideShowHiddens(action){
    $('.hidden_col').each(function(){
        if(action == 'show'){
            $(this).removeClass("hidden");
        }else{
            $(this).addClass("hidden");
        }
    });
}

Example: See JSFiddle example here

Alternative Approach:

For a more concise solution, consider this alternative approach:

function hideShowHiddens(action){
    (action === "show") ? $('.hidden_col').show() : $('.hidden_col').hide();
}

Answer №2

Make sure to include the $ selector in your code, like so: $(this).removeClass("hidden") and $(this).addClass("hidden");

Answer №3

The main issue is that the variable this refers to a DOM element and not a jQuery object. To solve this, you can simplify your code and eliminate the need for the .each loop:

function hideShowHiddens(action){
    $('.hidden_col').toggleClass('hidden', action !== 'show');
}

For more information, check out: https://api.jquery.com/toggleClass/#toggleClass-className-switch

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

Retrieve JSON data using AngularJS

Can someone guide me on how to make a GET request to my API endpoint and handle the JSON response in my code? Sample Controller.js Code: oknok.controller('listagemController', function ($scope, $http) { $scope.init = function () { ...

Retrieve a single record in Angular/Typescript and extract its ID value

There is data stored in a variable that is displayed in the Chrome console like this: 0: @attributes: actPer: "1", id: "19" 1: @attributes: actPer: "1" id: "17" etc To filter this data, the following code was used: myvar = this.obj.listR ...

Changing a string to uppercase and lowercase

I am currently working on a software that takes a string, divides it, capitalizes the first letter of the first string, and capitalizes all letters in the second string. Below is the code snippet: var fullName = "ThEoDORe RoOseVElT"; function nameEditor( ...

Error encountered: Difficulty rendering Vue 3 components within Google Apps Script

Currently delving into Vue and Vue 3 while coding an application on Google Apps Script. Following tutorials from Vue Mastery and stumbled upon a remarkable example by @brucemcpherson of a Vue 2 app functioning on GAS, which proved to be too challenging in ...

Exploring the JSON structure

Struggling to come up with a solution as I am limited by certain restrictions. I need to create a mobile navigation system using a JSON object provided by the proprietary server. The only allowed framework is jQuery 1.12.4, no other frameworks or updated v ...

Extract specific data from JSON objects

I have a JSON string that I need to parse on the client side in order to extract data for three different column names (MAT_ETHNICITY, PAT_ETHNICITY, SEX). My goal is to populate drop down lists with the values. Should I handle this by making three separ ...

Change the class of the div when the first div is selected

My goal is to switch the class of the #klapp element (from .klapp to .klappe) whenever a click event happens inside the #label-it container, including when the #klapp element itself is clicked. The challenge is that I am not able to use unique IDs for each ...

Tips for adjusting the minimum attribute within an input field with jQuery

In my form, I have an input field with arrows (up and down). Next to it, there are two buttons: + and -. When I click on the input field and then use the arrow, the system retrieves the value from a dropdown list, which works fine. However, when I use the ...

Looking to create a JSON array and iterate through its elements

I am in need of creating a state for multiple elements displayed on a web page. The states are limited to 1 or -1. My approach is to generate a JSON array on the server side and then embed it into my .aspx page like this: var someArray = { 100:-1, 1001: ...

Creating a Node API that can patiently listen for external data

My current project involves building a server that fetches data from an external API and returns it to the endpoint localhost:3000/v1/api/. However, I'm facing a challenge where the data retrieval process takes approximately 2 seconds, leading to empt ...

Encountered a failure while loading modules in AngularJS

When I tried opening the index.html page using Chrome, I encountered an error stating that the correct modules could not be found. Uncaught SyntaxError: Unexpected token < angular.js:1 Uncaught SyntaxError: Unexpected token < controller.js:1 ...

Exploring the nuances of useEffect() functionality and the impact of extra re-renders

I ran some tests using a dummy component and noticed an unusual pattern in the console output: Rendering: 0 Triggered: 0 Rendering: 4 Triggered: 4 Rendering: 4 I'm having trouble figuring out why this is happening. On the first render, the foll ...

Angular 2's solution for a persistent footer at the bottom of the page

I'm currently working on a project using Angular 2, and I'm looking to implement a sticky footer that always stays at the bottom of the page without being fixed. For reference, you can check out an example here: http://codepen.io/chriscoyier/pen/ ...

Determining the Size and Color of Squares in a Treemap Based on Content with D3.js

I encountered an issue with a treemap visualization. I came across an example that is similar to my situation, which can be viewed here: In the demo, you can see that the size of each square in the treemap is determined by the content size. However, all s ...

hapi-auth-cookie: encounters an issue while trying to read cookies for accessing restricted content

I've implemented hapi-auth-cookie for managing cookies and sessions on my website. Certain parts are restricted and can only be accessed after authentication. When a non-logged-in user tries to access these areas, they are redirected to the login rout ...

When trying to submit a form, encountering an `Uncaught ReferenceError` due to calling ajax within

Attempting to trigger an ajax function within a form in order to retrieve a value for the dropdown. mypython.py @app.route('/new_data', methods = ['POST', 'GET']) def new_data(): #Filter data and return the data(data_lis ...

Issue encountered when attempting to batch delete documents within a subcollection: Error message displays "TypeError: n.indexOf is not a

When attempting to batch delete a document within a subcollection, I encounter some issues. There are scenarios where I may need to remove the same product document ID along with various history document IDs, or multiple product document IDs with differen ...

Capture every URL path in NuxtJS page navigation

One interesting feature of NuxtJS is the ability to assign routes in a specific way. For instance, by naming a file pages/_book.vue, we can access the route localhost:3000/my-book with the parameter params.book set to "my-book". But what if some books ar ...

getting a null response when using the map feature - coding battles

Given an array filled with integers, my goal is to generate a new array containing the averages of each integer and its following number. I attempted to achieve this using the map function. var arr = [1,2,3,4]; arr.map(function(a, b){ return (a + b / ...

(Vue.js) The icon fails to be applied

<link rel="icon" href="/static/icons/apple-touch-icon.png" type="image/x-icon"> <link rel="icon" type="image/png" sizes="32x32" href="/static/icons/apple-touch-icon.png"> <link rel="icon" type="image/png" sizes="16x16" href="/static/ ...