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

Troubleshooting issue with file upload feature in Angular for Internet Explorer 9

I have implemented a file upload method using the following code: <input type="file" name="upload-file" ng-model= "excelFile" accept=".xlsx" onchange="angular.element(this).scope().fileChanged(this);" ...

The React router Link does not update the route after an if statement is executed

I'm in need of some assistance regarding React.js. Despite my efforts to find a solution, nothing has worked for me so far. Here are some examples of what I've searched for: How to use Redirect in the new react-router-dom of Reactjs Redirectin ...

Tips for configuring Webstorm to automatically change double quotes to single quotes when reformatting source code

After using cmd + alt + l in Webstorm to format my JavaScript code, I noticed that double quotes are used instead of single quotes. How can I configure Webstorm to automatically change the double quotes to single quotes in my code? ...

Issue with Angular modal text boxes failing to populate using ngModel

I am facing an issue with populating data in a modal when a table row is clicked. The table contains TV show data and uses dir-paginate/ng-repeat to display the information. However, when I click on a row to edit the show, the ng-model data does not load i ...

Using JavaScript to pass a newly created variable as an argument in a default

Currently, I am developing a node application that heavily utilizes promises. To enhance the readability of my code, I have been removing anonymous functions and storing them in a JavaScript object called "myCallbacks". Here's an example: let myCallb ...

"Encountering a problem with a missing object in jQuery when referencing

I'm encountering an issue with jQuery's $(this) object that's causing me to lose track of the this element in my code: $('.star').click(function (){ var id = $(this).parent().attr('id').split('rating')[ ...

Ways to shut down a pop-up

Can someone assist me with how to close the bio-info popup and implement it in the code provided below? The HTML file: <ul class="ch-grid"> <li> <div class="bioinfo"> <h2>tooltips</h2> /div> The CSS file: .bioinfo { ...

Tips for adjusting the font size of a Chip using Material-UI

I am using a widget called Chip const styles = { root:{ }, chip:{ margin: "2px", padding: "2px" } } const SmartTagChip = (props) =>{ const classes = useStyles(); return( <Chip style={{color:"white&q ...

Incorporate JSON when adding a new row to the database using Ruby On Rails

Greetings, fellow developers! I am currently working on an application with a backend in Rails. My goal is to create a user from an AJAX request and have the server return a JSON object containing the newly saved user information. Below is my Rails code s ...

Parallax not functioning properly due to CSS before and after elements

I am attempting to use before and after pseudo-elements for a parallax effect on my div element <div id="OurPhilosophy" class="parallax-window" data-parallax="scroll" data-image-src="https://cdn6.bigcommerce.com/s-jhmi7y5v2c/product_images/uploaded_ima ...

Execute AJAX request for two individual buttons

I have a scenario where I want to use two buttons to open separate PHP pages, but I would like to trigger both buttons with a single function. The AJAX function should then determine which button was clicked and open the corresponding PHP page - for exam ...

Sliding carousel from right to left

I'm currently working on setting up a slick carousel to continuously scroll, but I need it to move in the opposite direction. Despite trying to add the RTL option, I couldn't get it to work as intended. Check out my Fiddle here (currently scroll ...

Launching a React project using the terminal - my step-by-step process

I'm attempting to initiate a new react-app utilizing the command npx create-react-app <app name> as shown below: npx create-react-app new-app However, after downloading, it seems to be stuck. It's not progressing at all. I've even rei ...

Trouble displaying background image in Electron Application

When I try to load an image file in the same directory as my login.vue component (where the following code is located), it won't display: <div background="benjamin-child-17946.jpg" class="login" style="height:100%;"> A 404 error is popping up: ...

applying a timeout for the .on(load) event

My goal is to dynamically load images using .on('load') in the script below: .on('load', function() { if (!this.complete || typeof this.naturalWidth == "undefined" || this.naturalWidth == 0) { alert('broken i ...

Performing calculations with jQuery to extract the value of a selected dropdown option and a text

I am attempting to calculate the total amount by multiplying the value entered in a text box labeled qty1 by the price retrieved from a select box using ajax. <script type="text/javascript" charset="utf-8"> $(document).ready(function(){ ...

Steps for transferring data between two components

I'm looking for a way to transfer an object's id from one component to another. <ng-container matColumnDef="actions"> <mat-header-cell *matHeaderCellDef></mat-header-cell> <mat-cell *matCellDef="let user"> ...

Nothing is being returned when using JQuery AJAX POST

Having trouble identifying the issue, as all that seems to happen is the URL changes to "http://localhost/?search=test" when entering "test", for example. index.php <html> <head> <script src="https://ajax.googleapis.com/ajax/libs/jquer ...

Class-driven dynamic CSS

Recently, I came across a JSP code snippet that looks like this: <table id="mytable" cellspacing="0"> <tr data-depth="0" class="collapse level0"> <td></td> <td></td> <td></td> </tr> ////... /...// < ...

Is the script failing to retrieve the innerHTML content?

Here is a snippet of HTML code: <div id="team_players"> <h3>Players</h3> <button class="bold-btn" onclick="teamAct('player_list');">Refresh List ↻</button> <table> <thead> <tr> ...