Change CSS of class in Javascript?
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.
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");
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')
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; }