Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I change CSS properties dynamically without using the .css( ) method in JQuery?

Tags:

jquery

css

I have a div in my HTML code. I want to change it's background color to red (red for example, but it can be another color), but i don't want to use the .css() method in Jquery because the .css() method makes something like this in my HTML code:

<div id="my_div" style="background-color: red"> Elements inside my div </div>

I don't want the style attribute in my HTML code, but what can I do to change css dynamically whitout using that?

Updated: I can't use classes because the color won't always be red, it can be blue, yellow, purple, or an hexadecimal color.

like image 353
GalloPinto Avatar asked Mar 15 '26 03:03

GalloPinto


1 Answers

You can use CSS classes:

.red {
  background-color: red;
}

$("#my_div").addClass("red");

If you have more than one color, you can create multiple classes, but this somehow defeats the generalization purpose of using a class, as @pst mentioned in the comments, and you might be better using css() instead.

like image 119
João Silva Avatar answered Mar 17 '26 09:03

João Silva



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!