Add to a css class using JQuery

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");
}

  1. I have best example of how to apply CSS class in multiple tags.
  2. First create simple html page and inside write down your css.
  3. Next you create simple Query and and apply custom css.
  4. Now if you want apply which tag or attributes css using JQuery.
  5. 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 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.

Tags:

Css

Jquery