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...
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.
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.
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; }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With