Modify the CSS class by adding attributes dynamically instead of directly to the element

I encountered a situation where I needed to apply a css property to a class rather than an element.

For example:

    $('.class_with_css').css({display:'none'});

This code would add the style "display:none" to all elements with the class "class_with_css". However, I wanted to apply the "class_with_css" class to a new element after this and keep the added style. Is there a way to achieve this without calling the above function again?

For instance:

  1. Initial setup with two elements
    <div id=1 class="abc" ></div>
    <div id=2 class="abc" ></div>
  1. Run the code
    $('.abc').css({display:'none'});
  1. The elements become:
    <div id=1 class="abc" style="display: none;"  ></div>
    <div id=2 class="abc" style="display: none;" ></div>
  1. Add the "abc" class to a new element like this
    <div id=3 class="abc" ></div>

Is there a way to make the "abc" class hold the style instead of individual elements so that even the element in step 4 also has display:none?

Answer №1

Unfortunately, there is no direct way to achieve your desired result. Typically, this is done by already having a CSS class with the desired changes and properties, then applying that class instead of individual CSS properties.

For example, you would have:

.hide {
    display: none;
}

and then add the class to elements like so:

$('.abc').addClass('hide');

UPDATE
Alternatively, if you absolutely need to dynamically add a CSS class, you can refer to the solution provided here.

Answer №2

You have the ability to inject style into your header.

HOWEVER, KEEP IN MIND that once you do so, you will need to use display: block; to display it. Otherwise, by default, the style will be set to display: none; until you refresh the page.

The Inject() function injects style into your header.

The Add() function adds the "abc" class to other div elements.

The Showme() function sets "display: block" for elements with the ".abc" class.

The Hideme() function sets "display: none" for elements with the ".abc" class.

function Inject(){
  $('head').append('<style type="text/css">.abc {display: none;}</style>');
}
function Add() {
  $("#w").addClass("abc");
  $("#z").addClass("abc");
}
function Showme() {
 $(".abc").css("display","block");
}
function Hideme() {
 $(".abc").css("display","none");
}
button {
border: 0;
padding: 1% 3%;
background-color: lightgray;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="x" class="abc">x</div>
<div id="y" class="abc">y</div>
<div id="w">w</div>
<div id="z">z</div>
<p>First Click below and see how w and z are not hiding</p>
<button onclick="Inject()">Click to inject style to head</button>
<p>Second click below and add "abc" class to w and z.</p>
<button onclick="Add()">Click to add abc to w and z</button>
<p>Then click below to add style="display:block;"</p>
<button onclick="Showme()">Click to show anything with class "abc"</button>
<p>Then click below to add style="display:none;"</p>
<button onclick="Hideme()">Click to hide anything with class "abc"</button>

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

Storage in Ionic and variable management

Hello, I'm struggling to assign the returned value from a promise to an external variable. Despite several attempts, I have not been successful. export class TestPage { test:any; constructor(private storage: Storage) { storage.get('t ...

The jQuery toggle function is malfunctioning when applied to the rows of a table

I have been experimenting with toggling table rows using jquery. Initially, the state is hidden This feature is functioning properly $('.table tr.items.' + name).each(function() { $(this).show(); }); Furthermore, this snippet of code is wor ...

Sharing specific information with a particular component instance in React using .map

I have set up multiple instances of a child component within a parent component using the following code: render() { return ( {this.state.accounts.map(account => <EachAccount key={account.id} curAccountData={account} /> ...

Having trouble retrieving directive parameters in Vue.js?

Vue.directive('customselect', { params: ['selectedTask'], bind: function () { var that = this; $(this.el) .select2() .on('change', function () { that.set(this.value); if (!this.name.matc ...

javascript with python

Currently, I'm in the process of parsing a html page. I've experimented with spynner, selenium, and mechanize, however none of them have been effective when dealing with JavaScript in this particular scenario. Is there anyone who can provide som ...

Learn how to keep sessionStorage state synchronized across ReactJS components

Within my application, there is a React component responsible for displaying a list of numbers while also keeping track of the total sum of these numbers using sessionStorage. Additionally, another component provides an <input /> element to enable u ...

Incorporating a JavaScript advertisement zone within a PHP function

Currently in the PHP template, I am trying to embed a JavaScript ad zone inside a function in order to have control over each page's ad placement. Here is what I have: <?php if(is_page('welcome-president')) { oiopub_b ...

Anonymous self-executing functions with parameters from an external scope

Recently, I stumbled upon the code snippet below while following a tutorial. const increment = (function(){ return function incrementbytwo (number){ return number+2; } })(); console.log(increment(1)); The result of the code above is 3. ...

moving the array generated on the HTML page to a different page

Can anyone help me with transferring an array from one page to another? I have a list of names in the code below and I want to be able to access and print this array on another page using JavaScript. Your assistance is greatly appreciated! <html> ...

Tips for including a variable in formData and the steps for implementing it in an ajax procedure

<input type='file' name='inpfile' id='inpfile' accept='image/*' hidden> javascript code var clicked; $('#btnplusa').click(function(){ clicked = 'a'; $('#inpfile').click ...

What could be the reason for the CORS failure when making requests from an HTTPS domain to an HTTP localhost

I have a secure rest service (implemented as an Azure Function), hosted on HTTPS, under domain A. My website is also running securely on HTTPS but on domain B. I've set the CORS to use a wildcard *. Using jQuery on my website, I send Ajax requests ...

Instructions for user to upload and play an MP4 file on their PC

For my web project that utilizes node.js, HTML, and JavaScript, I am looking to incorporate a video player element. I want users to have the ability to click a button and play an MP4 file directly on the webpage. How can I achieve this? I currently have s ...

`sendNodejs header not being transmitted during connection``

My nodejs application utilizes stomp to connect to a server using websockets. However, I am encountering an issue where the application is failing to send the headers that I have specified. Despite referring to clear documentation and examples on how to in ...

Output Scalable Vector Graphics (SVG) content on a webpage

I need to include an SVG element in my Angular 2+ code. My goal is to provide users with the option to print the SVG element as it appears on the screen. <div class="floor-plan" id="printSectionId2" (drop)="onDrop($event)" (dragover)="onDragOver ...

Error encountered during Jest snapshot testing: Attempting to destructure a non-iterable object which is invalid

I am currently facing an issue with my React codebase where I am attempting to create snapshot tests for a component. However, Jest is showing an error indicating that I am trying to destructure a non-iterable instance. Despite thoroughly reviewing the cod ...

How to leverage async/await within loops in Node.js for optimized performance and efficiency

Hey there, I'm working on my nodejs api where I need to fetch data inside a loop and then perform another loop to save data in a different table. Can anyone guide me on how to achieve this? Below is a snippet of what I have attempted so far without su ...

"The file upload function is populating the req.body object, but not the req.file

I successfully implemented a file upload API using multer and express, which functions well when accessed through POSTMAN. However, I encountered an issue when trying to utilize the same API with another file upload API: The code I used can be found below ...

Develop a list of findings from the search

Is there a way to extract the name from the image shown below? return testData.then((data) => { console.log(data) var results = []; var toSearch = params.suggestTerm; data = data["data"]["0"]; console.log(" ...

Will Node applications be affected as newer versions of their dependencies are released, causing them to stop functioning properly?

I'm currently following an online tutorial on web development topics, and the associated code is hosted on GitHub. After downloading it, I noticed that the directory structure looks like this: E:\dev\angular-components-step-1>dir Direct ...

Attempting to download an image through an axios fetch call

There is an issue I am facing while trying to retrieve an image from the website www.thispersondoesnotexit.com. function getImage() { axios({ method: 'get', url: 'https://www.thispersondoesnotexist.com/image' }) ...