0

I'm messing around with vanilla JavaScript and I noticed that when styling a document with js in the DOM the styles are inline. Is there a way to style a style sheet with javascript used on the DOM or is styling with Javascript bad practice? I was thinking it might have some uses when parts of a website change with user interaction, but I'm guessing the same thing can be accomplished with css pseudo classes. To reiterate my question can you use javascript to style a stylesheet in the DOM or is it just inline and bad practice?

body.style.backgroundColor= "blue";

Brandon
  • 1,099
  • 1
  • 9
  • 14
  • 1
    Have you read e.g. https://developer.mozilla.org/en-US/docs/Web/Guide/CSS/Getting_started/JavaScript – jonrsharpe Jun 01 '16 at 06:54
  • 1
    I'd recommend preparing classes in your .css stylesheet and assigning them in javaScript. Writing css in JavaScript isn't really best practice. And yes it will always be inline styling. – noa-dev Jun 01 '16 at 06:57

1 Answers1

3

Best practice, in my opinion, is to create classes in separate CSS file and then change element classes using JS. It looks better and also it is easier to read and understand.

But if you want to, you can change stylesheet. Read this Is it possible to alter a CSS stylesheet using JavaScript? (NOT the style of an object, but the stylesheet itself)

Community
  • 1
  • 1
Nogi
  • 134
  • 9
  • @Kaiido No, what i'm trying to say is that when you use JS to change css directly it is inline. But there is a way to change stylesheet but it is more like workaround as you can see when you open given link. – Nogi Jun 01 '16 at 08:27
  • I know quite well how to play with styleSheets from js. This is not a workaround, just more complicated. The sentence "*writing CSS in JS will be always inline style*" is wrong, as shown by your link. There are other ways (maybe even more complicated) to write non-inlined CSS using js. What should be said is just that setting an element's style property will also change its style attribute. I'm not even sure we can call it *inline* since it's not inlined in the .html file but done by script. – Kaiido Jun 01 '16 at 08:40
  • Also, while in the general case it's true that it is a bad practice to use inline styles, I'd like to see how you'll handle some follow-the-mouse stylings and others, with classes. – Kaiido Jun 01 '16 at 08:41
  • Of course you need to use JS to style in some cases, thats why it is possible to do so. – Nogi Jun 01 '16 at 08:56
  • Maybe if author of this question could specify a situation we could give him more specific answer. – Nogi Jun 01 '16 at 08:59