Let's say you have a paragraph.
<pid="target">rainbow 🌈</p>
And you need to change it's color with JS. What options do you have?
1. Inline styles
The most straightforward path. Query the element from DOM and change it's inline styles.
document.getElementById('target').style.color='tomato';
Short and simple.
2. Global styles
Another option is to create<style>
tag, fill it with CSS rules and append the tag to the DOM.
varstyle=document.createElement('style');style.innerHTML=` #target { color: blueviolet; } `;document.head.appendChild(style);
3. CSSOM insertRule
Third option is less known. We gonna useCSSStyleSheetinsertRule
method.
varstyle=document.createElement('style');document.head.appendChild(style);style.sheet.insertRule('#target {color: darkseagreen}');
While it might look similar to the 2nd option, it's definitely different.
As you can see in Chrome devtools,<style>
tag is empty, but the style (darkseagreen color) is applied to the element. Also the color can't be changed via devtools because Chrome doesn't allowediting dynamic CSS styles.
Actually such behavior was the motivation to write this post. A popular CSS-in-JS libraryStyled Components use this feature to inject styles in production mode because of performance. This feature might be undesirable in specific projects or environments and some folks complain about it in the project's issues.
4. Constructable Stylesheets (July 2019 update)
It's now possible to createCSSStyleSheet
object from JavaScript.
// Create our shared stylesheet:constsheet=newCSSStyleSheet();sheet.replaceSync('#target {color: darkseagreen}');// Apply the stylesheet to a document:document.adoptedStyleSheets=[sheet];
More details arehere.
This option is only valid for Chrome, so use with caution.
Do you know other options to add styles with javascript? What is your preferred option these days?
Thanks for reading!
Top comments(14)

hey can you maybe help me ?
I have some things like this and I just want to Update the hidden class but I Update Complete Style
<style> .hidden{ animation-name: bgshower; animation-duration: 2s; position: absolute; z-index: 2; } .neopa{ background-color: darkred; font-size: large; }</style>
var style = document.getElementById('style');
var counter = parseInt(60);
style.innerHTML = ` .bghidden { height: 100%; width: 100%; background-color: #E96565; top: 0; left: 0; `+ 'animation-duration:' + counter + "s" + `; animation-name: bgshower; animation-delay: 0s; position: absolute; z-index: 2; } `; document.adoptedStyleSheets = [style];

I'm not 100% sure what you're trying to achieve, but if you need to add animations on an element(s) with JS after some event, consider the following way:
- Define styles with css like
.hidden{...}.animate{...}
- Add/remove CSS classes with animations when necessary with DOM API:
document.querySelectorAll('.hidden').classList.add('animate')

- LocationWarsaw, Poland
- WorkFront-end developer
- Joined
It's something I'm looking for. Thanks a lot!

- Locationhey there, unfortunately it is not possible for me to write new post due to website policiy.
- Joined
really great post i like it

Hi :D
I just wondered if using insertRule for performance or not and I found this article. Thanks !
But how it differ?

I don't think you ever need to useinsertRule
in your day-to-day job unless you hit some performance bottleneck when working with styles.
I think optimizations withinsertRule
are useful for libraries (likestyled-components
), but add unnecessary complexity when developing regular websites or apps.

style.setContent bug ❌
conststyle=document.createElement(`style`);// this.shadowRoot.appendChild(this.templateContent);// log(`this.shadowRoot`, this.shadowRoot);style.setContent=` .run { width: 100px; height: 100px; background: url(https://www.boston.com/wp-content/uploads/2016/05/yuge_anger.png) 0 0; animation: run 500 step(6) infinite; } @keyframes run { from { background-position: 0 0; } to { background-position: -600px 0; } } `;

- LocationRabat, MA
- EducationOFPPT
- WorkSelf Employed
- Joined
Thanks man for sharing, I was looking for something like this long ago
For further actions, you may consider blocking this person and/orreporting abuse