Changing attributes in a CSS class using jQuery

I can't figure out how to change an attribute in a CSS class. Right now I'm adding style to this particular div, but I want the attribute in the CSS class to be changed, and not just overridden by the new style attribute.

Example:

.example{background-color:blue} <div class="example">example</div> 

So, how can I change the background color in CSS.example, and not just override it like this:

 <div class="example" style="background-color:blue">example</div> 

I have tried many things, but I cannot figure it out. I tried .attr() and .css() , but I am missing something.

+4
source share
3 answers

You cannot change the actual CSS class (well, but it is very difficult and against practice), but you can change it for everything that applies to this class:

 $('.example').css('background-color', 'blue'); 

However, you can apply this CSS every time a new element of your type is generated. For example, after calling an AJAX script that retrieves data from another file:

 $('#blah').load('script.php', function() { $('.example').css('background-color', 'blue'); }); 

You may also have an interval that will be reapplied to all elements for you, but in terms of performance, this is not recommended:

 setInterval(function() { $('.example').css('background-color', 'blue'); }, 100); 

My advice to you was to find another way to mark your changes as a second class, and use this class to make changes to your elements.

+4
source

What you want is not possible, but something like this might be better.

 body.blueTheme .example { background-color: blue; } body.redTheme .example { background-color: red; } 

Now, instead of changing the color in the event handler, change the body class.

0
source

Dynamically changing stylesheets are generally bad ideas if you do not intend to implement full reuse.

It would be better to find another way to label elements so that they take on a different style, but if you do, you can dynamically change which stylesheets are loading.

Place the id element in the <style> element that references the external CSS file:

 <link id="dynCss" rel="stylesheet" type="text/css" href="..." /> 

and then put two different style options in two different CSS files.

and then you can use:

 document.getElementById('dynCss').href = ... 

or

 $('#dynCss).attr('href', ...); 

which will then load (and apply) the new styles in the new URL.

0
source

Source: https://habr.com/ru/post/1488307/


All Articles