27

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...

icyrock.com
28.7k4 gold badges72 silver badges92 bronze badges
asked Feb 5, 2012 at 22:32
5
  • Possible duplicate of stackoverflow.com/questions/622122/… Commented Feb 5, 2012 at 22:36
  • 9
    @j08691: No, that question is about jQuery. This one doesn't pre-suppose your use of that library. Commented Feb 5, 2012 at 22:46
  • You may look at this site quirksmode.org/dom/w3c_css.html Commented Feb 5, 2012 at 23:05
  • The default display property for a select element is inline-block, not block. You are much better off to toggle between none and '' (empty string) so that the element adopts its default display property when not set to none. Commented Feb 6, 2012 at 3:02
  • 1
    Yes but I specifically need "block" as attribute :-) Commented Feb 6, 2012 at 19:22

8 Answers 8

25

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.

answered Feb 5, 2012 at 22:51

3 Comments

Modifying rules makes sense where there are a large number of elements with the class to change, it is hugely faster than changing the elements one by one (which is what any selector based function must do). Delegating changes to a parent is pretty fast too.
Perfect good answer - you explain, that it is mostly not the best decision, but instead of trying to forbid something on philosophical reasons, you rather explain, how to do this if it would be needed. An example, as it could be useful: you have a lot of objects in the DOM, and modifying the class (and let the hard counting work to the C++ code of the browser) results a better app, as looping the elements by class selector (and doing the hard work from JS).
@peterh: Yeah, although the last time I tried this (a few weeks back, trying to answer a different question), it seemed like rules had become read-only. I never had time to follow up on that...
18

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;
}
answered Feb 5, 2012 at 22:46

2 Comments

Thank you! This works for me: var selects = document.getElementsByTagName("select"); for(var i =0, il = selects.length;i<il;i++){ selects[i].style.display="none"; }
instead of i.e. .className += " hidden" you can use .classList.Add("hidden"). It is a little bit more performant and better maintainable.
15

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.

Martin Tournoij
28k24 gold badges110 silver badges158 bronze badges
answered Jan 10, 2013 at 1:02

4 Comments

This worked fine in firefox 21, opera 12.12 and ie 10 as well. More elaborate selector rules also work. css_getclass('td:first-child a img').style.width=this.value+"em";
Note by compatibility you need change dsi=ds[i].cssRules to dsi=ds[i].cssRules||ds[i].rules and be aware that the funcion will overwritte rules if the same selectorText exists in a previous styleSheet.
I'm not sure if that's the reason, but it seems to me that this only works if the class exists in a separate stylesheet file (and not in the html tag) and it doesn't seem to work with specifics like kbd.myclass.
Also, it's important to note that as of chrome 64, this won't work locally anymore but it seems to still be working in edge 40
5

You can edit the style sheets, but I would think you would just create a new class instead. If you really need to do it, try this.

 ss=document.styleSheets[0]

cssRules Are the style sheet rules

 ss.cssRules
 ss.cssRules[0]

Selector for the first rule

 ss.cssRules[0].selectorText
 ".channel > li"

Read the style of the first rule

 ss.cssRules[0].style
 CSS2Properties { "margin-left" → "0px"}

Change the style

 ss.cssRules[0].style.marginLeft="15px"
 ss.cssRules[0].style

CSS2Properties { "margin-left" → "15px" }

answered Oct 27, 2018 at 2:53

Comments

3

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>

answered May 19, 2017 at 10:16

1 Comment

Clever and simple. Plus, it works in ios 12, iPhone (WKWebView). +1
1

To get the same effect, you can make another style:

<style type="text/css">
 .fool select {
 display: block;
 }
 .foolnone select {
 display: none;
 }
</style>

and change the class of <p> to foolnone.

Otherwise, you'd have to go through each of the children of <p> and change the class. If that's the way you want to go, probably probably best to use some library, such as jquery. With it, you can do something like:

<style>
.fool select.displaynone {
 display: none
}
$('.fool>select').toggleClass('displaynone')

See this jsfiddle for a working example:

This shows both above approaches (i.e. hiding the whole <p> and hiding each of the <select>s.

answered Feb 5, 2012 at 22:36

2 Comments

I'd always prefer to add another class, and define a different style rule using a longer selector, rather than changing the class as the existing class "fool" could be used for other things too and it might not be safe to remove it entirely
@wheresrhys Completely agree - see the example I added, showing both approaches. It adds displaynone class for this. However that fits into your project is something you can ponder on, but this should be what you can use basically, details aside.
0

I think it would work if instead put like this:

var elements = document.getElementsByTagName('select');
for(var i = 0; i < elements.length; i++){
 elements[i].style.display = 'none';
}
answered Apr 27, 2020 at 23:12

1 Comment

I've meant to reply to Gabe's snippet and somehow landed here
-1
 for(var elements = document.getElementsByTagName('select'), i = elements.length; i--)
 elements[i].style.display = "none";
answered Feb 5, 2012 at 22:49

1 Comment

Doesn't work (even replacing "," with ";" before "i = ..." This is the error: "Uncaught TypeError: Cannot read property 'style' of undefine"

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.