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?
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.
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.
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.
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.
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; }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With