Monday, June 3, 2024
 Popular · Latest · Hot · Upcoming
34
rated 0 times [  39] [ 5]  / answers: 1 / hits: 38835  / 8 Years ago, sat, october 1, 2016, 12:00:00

Goal



In my program I want to do both things with jquery/javascript:




  1. Change styling of css classes dynamically

  2. Add/remove classes to elements



Problem



To do the first thing I use $(.className).css() method, but it changes style only for those elements that already have className class, i.e. if I later add className to an element its style won't be new. How can I solve this?



Example



See it also at jsfiddle.





$(p).addClass(redclass);
$(.redclass).css(color, darkRed);
$(span).addClass(redclass);

<script src=https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js></script>
<p>I want to be red! And I am.</p>
<span>I want to be red too but I'm not :'(</span>





Result:



enter


More From » jquery

 Answers
9

A more shorten format:



$(<style/>, {text: .redclass {color: darkRed;}}).appendTo('head');


The snippet:





$(<style/>, {text: .redclass {color: darkRed;}}).appendTo('head');


$(p).addClass(redclass);

$(span).addClass(redclass);

<script src=https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js></script>


<p>I want to be red! And I am.</p>
<span>I want to be red too but I'm not :'(</span>




[#60539] Wednesday, September 28, 2016, 8 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
nikokorbinm

Total Points: 744
Total Questions: 126
Total Answers: 104

Location: Jersey
Member since Fri, Oct 1, 2021
3 Years ago
;