Add to css class using jQuery

Is it possible to add / update a css class using jQuery.

I know that I can add css to the DOM element using this add css rule using jquery , but I would like to add / remove from the css class itself.

+7
source share
5 answers

You cannot directly update CSS classes in a separate css file using jQuery. However, you can create the <style> and add / overwrite the CSS class:

 $('<style>.newClass { color: red; }</style>').appendTo('body'); 

When updating the CSS class, you need to take care of the cascading order . Otherwise, perhaps this will not be a consequence of the effect.

+14
source

If I understand what you are trying to do, I believe that this should work for you.

 $("#UniqueName").remove(); $("<style id="UniqueName" type='text/css'> .MyClass{ color:#f00 !important; font-weight:bold !important;} </style>").appendTo("head"); 

It is best to have logical little classes and use the jQuery .toggleClass() method .

 .Bold{ font-weight:bold; } .Italic {font-style:italic;} function SwitchFont(){ $(".MyObjects").toggleClass("Bold"); $(".MyObjects").toggleClass("Italic"); } 
+4
source

It's too easy to use the latest versions of jQuery using something like this:

 $('jQuery selector').css({"css property name":"css property value"}); 

For example:

 $('#MyDiv').css({"background-color":"red"}); 
+3
source

You can do this using the addClass and removeClass functions in jquery. Add the class as follows:

 $("#button1").click(function(){ $(#the_div).addClass('myClass'); }); 

Then you can remove it as follows:

 $("#button2").click(function(){ $("#the_div").removeClass('myClass'); }); 

Your CSS properties must be defined in ".myClass".

-one
source

If you want to add a new class or properties, use add class

http://api.jquery.com/addClass/

which will add properties to the DOM elements.

If you want to overwrite existing properties, use jquery.css, in your case Update

http://api.jquery.com/css/

.css will add as an inline style, so all your class properties will be overwritten

-one
source

All Articles