Set CSS Styles With Javascript - DEV Community
Maybe your like
Let's say you have a paragraph.
<p id="target">rainbow 🌈</p> Enter fullscreen mode Exit fullscreen modeAnd 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'; Enter fullscreen mode Exit fullscreen mode
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.
var style = document.createElement('style'); style.innerHTML = ` #target { color: blueviolet; } `; document.head.appendChild(style); Enter fullscreen mode Exit fullscreen mode
3. CSSOM insertRule
Third option is less known. We gonna use CSSStyleSheet insertRule method.
var style = document.createElement('style'); document.head.appendChild(style); style.sheet.insertRule('#target {color: darkseagreen}'); Enter fullscreen mode Exit fullscreen modeWhile 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 allow editing dynamic CSS styles.
Actually such behavior was the motivation to write this post. A popular CSS-in-JS library Styled 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 create CSSStyleSheet object from JavaScript.
// Create our shared stylesheet: const sheet = new CSSStyleSheet(); sheet.replaceSync('#target {color: darkseagreen}'); // Apply the stylesheet to a document: document.adoptedStyleSheets = [sheet]; Enter fullscreen mode Exit fullscreen modeMore details are here. 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!
Tag » Add Css Property To Element Javascript
-
How To Add Styles To An Element - JavaScript Tutorial
-
JavaScript HTML DOM - Changing CSS - W3Schools
-
Add CSS Attributes To Element With JavaScript - Html - Stack Overflow
-
Add A CSS Property To An Element With JavaScript/jQuery
-
Two Ways To Set An Element's CSS With Vanilla JavaScript
-
How To Set Style To An HTML Element Using JavaScript - Tabnine
-
yle - Web APIs | MDN
-
Dynamic Style - Manipulating CSS With JavaScript - W3C Wiki
-
How To Change CSS With JavaScript [With Examples] - Alvaro Trigo
-
Setting CSS Styles Using JavaScript | KIRUPA
-
.css() | JQuery API Documentation
-
Javascript Add Style To Element | TutorialsTonight
-
DOM Elements - React
-
Check If Element's Style Contains CSS Property Using JS | Bobbyhadz