Is it possible to add/update a css class using JQuery.
I know I can add css to a DOM element using this add css rule using jquery, but I would like to add/remove from the css class itself.
Is it possible to add/update a css class using JQuery.
I know I can add css to a DOM element using this add css rule using jquery, but I would like to add/remove from the css class itself.
You cannot directly update the CSS classes in a separate css file with jQuery. You could however create a <style>
tag and add/overwrite a CSS class:
$('<style>.newClass { color: red; }</style>').appendTo('body');
When updating a CSS class, you'll need to take care the cascading order. Otherwise, it may not turn out to be the effect you are after.
It's too easy using the lastest versions of Jquery, using something like this:
$('jQuery selector').css({"css property name":"css property value"});
For example:
$('#MyDiv').css({"background-color":"red"});
If I understand what you are trying to do I believe 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'd be best to have logical small classes, and use jQuery's .toggleClass()
method.
.Bold{ font-weight:bold; }
.Italic {font-style:italic;}
function SwitchFont(){
$(".MyObjects").toggleClass("Bold");
$(".MyObjects").toggleClass("Italic");
}
When I write down this code to easily understand
Code:
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
$("#btn1").click(function(){
$("h1,p").toggleClass("blue");
$("div").toggleClass("important");
});
});
</script>
<style>
.important {
font-weight: bold;
font-size: 40px;
color: chartreuse;
}
.blue{
color: #000080;
}
</style>
</head>
<body>
<h1>This is example</h1>
<p>This is example</p>
<div>Some important message </div>
<button id="btn1">Add class </button>
</body>
</html>
You can do this by using the addClass and removeClass functions in jquery. Add the class like this:
$("#button1").click(function(){
$(#the_div).addClass('myClass');
});
Then you can remove it like this:
$("#button2").click(function(){
$("#the_div").removeClass('myClass');
});
Your CSS properties should be defined in ".myClass".
If you want to add new class or properties use add class
http://api.jquery.com/addClass/
which will add the properties to the DOM elements.
If you want to overwrite the existing properties use jquery .css , in your case Update
.css will add as an inline style , so all your class properties will be overwritten