Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Change CSS of class in Javascript?

Tags:

javascript

css

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?

like image 700
Skizit Avatar asked Apr 22 '11 08:04

Skizit


People also ask

Can I change CSS class in JavaScript?

JavaScript offers us two properties that we can use to modify CSS classes; classList and className property. The className property is used to set a value to a CSS class directly whereas the classList gives us some built-in methods to manipulate the CSS classes.

How do you change classes in CSS?

class selector selects elements with a specific class attribute. To select elements with a specific class, write a period (.) character, followed by the name of the class.

How do I change the class property in CSS?

Set Style Using element. One can use element. className to change various style parameters of an HTML element by clubbing those as a class and assigning the class name to the selected element with element. className . This method is helpful, especially in scenarios where we need to display an error in an input field.


2 Answers

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.

like image 182
T.J. Crowder Avatar answered Sep 21 '22 13:09

T.J. Crowder


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; } 
like image 22
Znarkus Avatar answered Sep 22 '22 13:09

Znarkus