36

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
  • 85,173
  • 29
  • 368
  • 345
Skizit
  • 43,506
  • 91
  • 209
  • 269

8 Answers8

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,821
  • 2
  • 20
  • 21
T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875
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; }
Markus Hedlund
  • 23,374
  • 22
  • 80
  • 109
  • Claims there's no such method as `getElementsByClassName` for `document` – Skizit Apr 22 '11 at 08:49
  • 2
    Hrm, it's not supported by [older IE](http://www.quirksmode.org/dom/w3c_core.html#fivemethods). I'd honestly recommend something like jQuery, but get bashed every time I suggest it. – Markus Hedlund Apr 22 '11 at 08: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](http://jquery.com), [Prototype](http://prototypejs.org), [YUI](http://developer.yahoo.com/yui/), [Closure](http://code.google.com/closure/library), or [any of several others](http://en.wikipedia.org/wiki/List_of_JavaScript_libraries) can smooth over browser differences for you, and provide lots of useful utilities. – T.J. Crowder Apr 22 '11 at 09:19
  • @Skizit: You can add `getElementsByClassName` to browsers that don't support it: http://ejohn.org/blog/getelementsbyclassname-speed-comparison/ – T.J. Crowder Apr 22 '11 at 09: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')
Spoike
  • 119,724
  • 44
  • 140
  • 158
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");
Soyoes
  • 940
  • 11
  • 16
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
Community
  • 1
  • 1
tomasb
  • 1,663
  • 2
  • 22
  • 29
  • 2
    finally, a good answer:) I edited it and added a "value" input to immediately change the rule – guy_m Feb 10 '15 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. – Mike Aug 08 '19 at 01: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.

Remigius Stalder
  • 1,921
  • 2
  • 26
  • 31
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>
Kamil Kiełczewski
  • 85,173
  • 29
  • 368
  • 345
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');
changelog
  • 4,646
  • 4
  • 35
  • 62
  • 2
    Pfft! What's not Javascript about jQuery? ;-) – changelog Apr 22 '11 at 08:44
  • 8
    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. – cHao Apr 27 '11 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:" – user229044 Apr 27 '11 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. – changelog Apr 28 '11 at 08: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.) – cHao May 02 '11 at 23:48