Philip Voronov Philip Voronov - 2 months ago 12
CSS Question

How to dynamically change a class css styling?

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.

HTML:

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


JS:

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


Result:

enter image description here

Answer

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>