Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Change the style of an entire CSS class using javascript

Tags:

Is there a way to change an attribute of a CSS class using javascript?

<style type="text/css">   .fool select {     display: block;   } </style>  <p class="fool">   <select id="a" onchange="changeCSS()"> ... </select>   <select id="b" > ... </select>   <select id="c" > ... </select> </p> 

I want to change display:block to display:none for ALL <select> elements after a user call function changeCSS().

It looks simple but I can't find a way to do this...

like image 607
Bedo Avatar asked Feb 05 '12 22:02

Bedo


People also ask

Can you change a CSS class with JavaScript?

With JavaScript, we are able to set CSS styles for one or multiple elements in the DOM, modify them, remove them or even change the whole stylesheet for all your page.


2 Answers

You can modify style rules, but it's usually not the best design decision.

To access the style rules defined by style sheets, you access the document.styleSheets collection. Each entry in that collection will have a property either called cssRules or rules depending on the browser. Each of those will be a CSSRule instance. You can change the rule by changing its cssText property.

But again, that's probably not the best way to solve the problem. But it is the literal answer to your question.

The best way to solve the problem is probably to have another class in your stylesheet that overrides the settings of the previous rule, and then to add that class either to the select elements or to the container of them. So for instance, you could have the rules:

.fool select {     display: block; } .fool.bar select {     display: none; } 

...and when you want to hide the selects, add the "bar" class to the container that has the "fool" class.

Alternately, apply CSS style information directly to elements.

like image 137
T.J. Crowder Avatar answered Oct 10 '22 20:10

T.J. Crowder


The key is to define extra rules for additional classes and add these classes to the elements rather than to rewrite the rules for a given style rule.

JS

function changeCSS() {   var selects = document.getElementsByTagName("select");   for(var i =0, il = selects.length;i<il;i++){      selects[i].className += " hidden";   } } 

CSS

.fool select.hidden, select.hidden {    display: none; } 

Or for a really efficient method (but which might need a few more specific style rules too)

JS

function changeCSS() {   document.getElementsByTagName("body")[0].className += " hideAllSelects" } 

CSS

body.hideAllSelects select {    display: none; } 
like image 26
wheresrhys Avatar answered Oct 10 '22 21:10

wheresrhys