Change CSS rules using JavaScript or jQuery?

Is it possible to edit / modify existing css rules using javascript or jquery? For example, a stylesheet has this class:

.red { color: red; } 

And I have 10 elements using the class.

What I would like to do is change the class as follows:

 .red { color: blue; } 

Thus, it will also affect future instances of the same class. (11, 12, 13 elements, etc.).

0
source share
5 answers

Here's how you modify the CSS rule using JavaScript.

 var ss = document.styleSheets; var m = document.getElementById('modifiedRule'); for (i = 0; i < ss.length; i++) { var rules = ss[i]; for (j = 0; j < rules.cssRules.length; j++) { var r = rules.cssRules[j]; if (r.selectorText == ".red") { m.innerHTML = "<br />Old rule: " + r.cssText; r.style.color = "blue"; m.innerHTML += "<br />Modified rule: " + r.cssText; } } } 
 .red { color: red; } 
 <div class="red">Text</div> <div class="red">Text</div> <div class="red">Text</div> <div class="red">Text</div> <div class="red">Text</div> <div class="red">Text</div> <div class="red">Text</div> <div id="modifiedRule"></div> 
+1
source

Javascript provides a collection of document.stylesheets that provides a list of CSSStyleSheet objects. You can go through this collection to find any specific css rule that interests you and change its rules.

However, as mentioned above, this is probably not the right approach to what you are trying to achieve. It may be a bit of a browser and just feels hacked.

You will be better off having 2 separate rules.

 .red { color :red } .blue { color : blue } 

Inside your javascript, a variable is supported that contains the current default class for your elements, i.e. current_class = 'blue'. When you create an element simply .addClass (current_class). If you want to change all elements, .toggleClass (current_class, new_class).

+1
source

I think you could just do this:

 var reds = $('.red'); var index = 1; reds.each(function(){ $(this).css('color', index > 10 ? 'blue' : 'red'); index++; }) 
0
source

What you ask seems to me to be an abuse of CSS (regardless of whether you find a suitable solution for a specific question).

I would approach this as follows:

 .red .myElementClass{ /*or perhaps .red>.myElementClass*/ color:red; } .blue .myElementClass{ /*or perhaps .blue>.myElementClass*/ color:blue; } 

 <div id="outer" class="red"> <div class="myElementClass">foo</div> <div class="myElementClass">foo</div> <div class="myElementClass">foo</div> <div class="myElementClass">foo</div> <div class="myElementClass">foo</div> <div class="myElementClass">foo</div> </div> 

Now you can add as much as you want and change all your colors, just change the div#outer class to blue .

-1
source

I believe jQuery.css () is what you are looking for.

 $('.red').css('color', 'blue'); 

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

-3
source

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


All Articles