1

For example, I have a class .text-center which has no style rules.

The class is used on a div like this:

<div id="div" class="text-center"> 
   ... some HTML elements
</div>

I want to add this rule to the class:

display:none

Is there any way to do that with JavaScript?

isherwood
  • 52,576
  • 15
  • 105
  • 143
  • 1
    I don't think you can add a style to a class in CSS through JS – evolutionxbox Dec 17 '21 at 14:12
  • 1
    You've tagged this [tag:node.js] (although isherwood has edited that out, which I think is a dangerous assumption). What is the relationship between your CSS and Node.js? Are you using any kind of CSS parser? Are you trying to manipulate plain strings? – Quentin Dec 17 '21 at 14:12
  • @evolutionxbox — Browsers have built-in APIs for modifying CSS rulesets which can be accessed with JS in a browser … but this question is about Node.js so we can't use those here. There might be a library which will help on NPM but I don't know of one off the top of my head. – Quentin Dec 17 '21 at 14:14
  • If this was a question about JS running in a browser then https://stackoverflow.com/questions/1409225/changing-a-css-rule-set-from-javascript would be a good duplicate target. – Quentin Dec 17 '21 at 14:16
  • 1
    You're confusing CSS class _rules_ with the class attribute on an HTML element. Not quite the same thing. – isherwood Dec 17 '21 at 14:16
  • You're also asking an [xy question](http://xyproblem.info), about a proposed solution to your problem rather than the problem itself. Please revise to not do that. – isherwood Dec 17 '21 at 14:18
  • I'm new to coding and I might be confused about topics and terms. I'm sorry for that. Next time I'll be more careful when asking questions. – Alim Gölcük Dec 17 '21 at 14:31

1 Answers1

-1
  const els = document.getElementsByClassName("text-center");
  Array.prototype.forEach.call(els, function (el) {
    el.style.display = "none";
  });
Reza Ghorbani
  • 361
  • 1
  • 11
  • 1
    That will throw an error. `getElementsByClassName` returns a node list, not an element. `style` is undefined. – Quentin Dec 17 '21 at 14:17
  • You could loop over the list and modify each element, but the question is about changing the stylesheet not the elements. Changing the stylesheet would have different behaviour (given specificity and/or dynamically added elements) – Quentin Dec 17 '21 at 14:18
  • I have modified the answer and now it works! Please try it again. – Reza Ghorbani Dec 17 '21 at 14:49
  • It still modifies the elements in the DOM instead of the stylesheet. – Quentin Dec 17 '21 at 14:53