Marl Marl - 5 months ago 27
Javascript Question

jQuery CSS: Dynamically change attributes of a class

I want to change the attribute of a class on which all element that use the class for the rest of the web application life (from start of use until the user exits the web application) will be affected.


<p class="myClass">
<p class="myClass">


background-color: #ffff00;


$(".myClass").css("background-color", "#00FFFF");
$("p").last().after("<div class='myClass'>Now!</div>");

Here is a sample

What I want to achieve from the sample is that all subsequent dynamically added myClass will have the new attribute. From the jsFiddle, you'll see that the next added element doesn't have the new attribute.


I'm just using the color for a basis, I will implement this in larger scale, what I want to accomplish is to dynamically change the attributes of a class that will be used for the entire web app life cycle.


Using the css() method changes the inline styles on already existing elements, and you can't use that to change the styles on future elements. A workaround (that I don't like very much) would be to insert a style tag:

$( "<style>.myClass {background-color : #00FFFF}</style>" ).appendTo( "head" )
$("p").last().after("<div class='myClass'>Now!</div>");