Change the style of an entire CSS class using javascript
Solution 1:
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.
Solution 2:
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;
}
Solution 3:
I'm accessing CSS classes directly to adjust the height of a bunch of divs simultaneously. This is how I'm doing it:
function cssrules() {
var rules = {};
for (var i=0; i<document.styleSheets.length; ++i) {
var cssRules = document.styleSheets[i].cssRules;
for (var j=0; j<cssRules.length; ++j)
rules[cssRules[j].selectorText] = cssRules[j];
}
return rules;
}
function css_getclass(name) {
var rules = cssrules();
if (!rules.hasOwnProperty(name))
throw 'TODO: deal_with_notfound_case';
return rules[name];
}
and then you can do something like css_getclass('.classname').style.background="blue"
. I only tried this on chrome for windows, good luck with other browsers.
Solution 4:
Here's how I'd do it:
//Broken up into multiple lines for your convenience
setTimeout
(
function()
{
document.getElementById('style').innerHTML = 'p.myclass{display: none}';
}, 5000
);
<!--Should this be separated into "<head>"?-->
<style id="style"></style>
<p>After 5 seconds:</p>
<p>This text won't be hidden,</p>
<p class="myclass">But this will,</p>
<p class="myclass">And so will this.</p>
<script>
style = document.getElementById('style');
setTimeout(function(){style.innerHTML = 'p.myclass{display: none}'}, 5000);
</script>