37

I've got a class with the display set to none I'd like to in Javascript now set it to inline I'm aware I can do this with an id with getElementById but what's the cleanest way to do it with a class?

Kamil Kiełczewski
93.5k34 gold badges400 silver badges373 bronze badges
asked Apr 22, 2011 at 8:33
2
  • 3
    Just for future reference, because I think it closely resembles what you want: hunlock.com/blogs/Totally_Pwn_CSS_with_Javascript Commented Apr 22, 2011 at 8:41
  • @Zirak Unfortunately, that link is broken Commented Feb 5, 2021 at 19:51

8 Answers 8

22

You can do that — actually change style rules related to a class — using the styleSheets array (MDN link), but frankly you're probably better off (as changelog said) having a separate style that defines the display: none and then removing that style from elements when you want them no longer hidden.

Zefiro
2,8512 gold badges20 silver badges21 bronze badges
answered Apr 22, 2011 at 8:39
17

Do you mean something like this?

var elements = document.getElementsByClassName('hidden-class');
for (var i in elements) {
 if (elements.hasOwnProperty(i)) {
 elements[i].className = 'show-class';
 }
}

Then the CSS

.hidden-class { display: none; }
.show-class { display: inline; }
answered Apr 22, 2011 at 8:39
4
  • Claims there's no such method as getElementsByClassName for document Commented Apr 22, 2011 at 8:49
  • 2
    Hrm, it's not supported by older IE. I'd honestly recommend something like jQuery, but get bashed every time I suggest it. Commented Apr 22, 2011 at 8:54
  • 1
    @Zharkus: No harm in recommending using a library as an adjunct or postscript to an answer that doesn't require one (said one of the bashers); it's when someone answers a non-jQuery question with a purely jQuery answer that it's in appropriate. @Skizit: A library ilke jQuery, Prototype, YUI, Closure, or any of several others can smooth over browser differences for you, and provide lots of useful utilities. Commented Apr 22, 2011 at 9:19
  • @Skizit: You can add getElementsByClassName to browsers that don't support it: ejohn.org/blog/getelementsbyclassname-speed-comparison Commented Apr 22, 2011 at 9:23
14

You can use getElementsByClassName in which you'll get an array of elements. However this is not implemented in older browsers. In those cases getElementsByClassName is undefined so the code has to iterate through elements and check which ones have the desired class name.

For this you should use a javascript framework such as jQuery, mootools, prototype, etc.

In jQuery it could be done with a one-liner as this:

$('.theClassName').css('display', 'inline')
answered Apr 22, 2011 at 8:45
1
  • 1
    Wrong, that should be $('.theClassName').css('display', 'inline') Commented Apr 22, 2011 at 8:50
10

you can create new style rule instead.

var cssStyle = document.createElement('style');
cssStyle.type = 'text/css';
var rules = document.createTextNode(".YOU_CLASS_NAME{display:hidden}");
cssStyle.appendChild(rules);
document.getElementsByTagName("head")[0].appendChild(cssStyle);
$("#YOUR_DOM_ID").addClass("YOUR_CLASS_NAME");
answered Nov 18, 2012 at 1:59
6

You may like to exploit/rewrite this function:

function getStyleRule(ruleClass, property, cssFile) {
 for (var s = 0; s < document.styleSheets.length; s++) {
 var sheet = document.styleSheets[s];
 if (sheet.href.endsWith(cssFile)) {
 var rules = sheet.cssRules ? sheet.cssRules : sheet.rules;
 if (rules == null) return null;
 for (var i = 0; i < rules.length; i++) {
 if (rules[i].selectorText == ruleClass) {
 return rules[i].style[property];
 //or rules[i].style["border"]="2px solid red";
 //or rules[i].style["boxShadow"]="4px 4px 4px -2px rgba(0,0,0,0.5)";
 }
 }
 }
 }
 return null;
}
  • to scan all style sheets attached pass "" as third argument, otherwise something like "index.css"
  • ruleClass contains starting '.'
  • if (rules[i].selectorText && rules[i].selectorText.split(',').indexOf(property) !== -1) condition improvement found here https://stackoverflow.com/a/16966533/881375
  • don't forget to use javascript syntax over css properties, e.g. box-shadow vs. boxShadow
answered Oct 4, 2013 at 3:42
2
  • 2
    finally, a good answer:) I edited it and added a "value" input to immediately change the rule Commented Feb 10, 2015 at 17:15
  • This was the answer for me as well. Changing the styles of the elements didn't work because some elements are added to the dom via media query (after the event when elements were changed). I'm on a React JS project so the CSS is transpiled into the html. So I had to kill the test for href. Commented Aug 8, 2019 at 1:03
2

Although this is long gone, here a few remarks:

  • Using display: inline to make things visible again may spoil the page flow. Some elements are displayed inline, others block etc. This should be preserved. Hence, only define a .hidden style and remove it to make things visible again.

  • How to hide: There are (at least) two ways to hide elements, one is the above mentioned display: none which basically makes the element behave as if it was not there, and the visibility: hidden which renders the element invisible but keeps the space it occupies. Depending on what you want to hide, the visibility may be a better choice, as other elements will not move when showing/hiding an element.

  • Adding/removing classes vs. manipulating CSS rules: The result is quite different. If you manipulate the CSS rules, all elements having a certain CSS class are affected - now and in the future, i.e. new elements dynamically added to the DOM are also hidden, whereas when you add/remove a class, you must make sure that newly added elements also have the class added/removed. So, I'd say adding/removing classes works well for static HTML, whereas manipulating CSS rules might be a better choice for dynamically created DOM elements.

answered Sep 19, 2014 at 14:55
2

To change CLASS you need to edit document stylesheets

[...document.styleSheets[0].cssRules].find(x=> x.selectorText=='.box')
 .style.display='inline';

[...document.styleSheets[0].cssRules].find(x=> x.selectorText=='.box')
 .style.display='inline';
.box {
 margin: 10px;
 padding: 10px;
 background: yellow;
 display: none
}
<div class="box" >My box 1</div>
<div class="box" >My box 2</div>
<div class="box" >My box 3</div>

answered Apr 2, 2019 at 6:29
0

Best way to do it is to have a hidden class, like so:

.hidden { display: none; }

After that, there is a className attribute to every element in JavaScript. You can just manipulate that string to remove occurrences of the hidden class and add another one.

One piece of advice: Use jQuery. Makes it easier to deal with that kind of stuff, you can do it like:

$('#element_id').removeClass('hidden').addClass('something');
answered Apr 22, 2011 at 8:36
5
  • 2
    Pfft! What's not Javascript about jQuery? ;-) Commented Apr 22, 2011 at 8:44
  • 9
    The fact that jQuery-specific code doesn't work in plain-vanilla JS, if jQuery isn't included? "Use jQuery" isn't always a valid answer to every question about JS, and i'm sure some people get tired of hearing it. Commented Apr 27, 2011 at 11:51
  • 2
    Generally your answer shouldn't introduce jQuery if it wasn't mentioned in the question. If you really want to include jQuery, should answer in vanilla JavaScript and add a "...however, in jQuery, it would look like this:" Commented Apr 27, 2011 at 15:49
  • 2
    If you bothered reading the answer, you'd see that I go and explain how to do it in vanilla JavaScript, and then, and only then do I recommend jQuery. Commented Apr 28, 2011 at 8:27
  • The only JS i see in the answer is jQuery-specific. If you'd shown an example of how to do it otherwise, i'd probably have upvoted the answer. (I didn't downvote, but mostly because i feel -1 is enough of a point.) Commented May 2, 2011 at 23:48

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.