how to create a style element in js (many ways) create style in js style element Shadow DOM CSSStyleSheet adoptedStyleSheets
create style in js
Constructed StyleSheets
CSSStyleSheet
adoptedStyleSheets
Shadow Roots (Shadow DOM)
Documents
demo
// Create our shared stylesheet:
const sheet = new CSSStyleSheet();
sheet.replaceSync('a { color: red; }');
// Apply the stylesheet to a document:
document.adoptedStyleSheets = [sheet];
// Apply the stylesheet to a Shadow Root:
const node = document.createElement('div');
const shadow = node.attachShadow({ mode: 'open' });
shadow.adoptedStyleSheets = [sheet];
https://developers.google.com/web/updates/2019/02/constructable-stylesheets
insertAdjacentHTML
document.head.insertAdjacentHTML("beforeend", `<style>body{background:red}</style>`)
styleSheet.cssText
const styleNode = document.createElement('style');
styleNode.type = "text/css";
// browser detection (based on prototype.js)
if(!!(window.attachEvent && !window.opera)) {
styleNode.styleSheet.cssText = 'span { color: rgb(255, 0, 0); }';
} else {
var styleText = document.createTextNode('span { color: rgb(255, 0, 0); } ');
styleNode.appendChild(styleText);
}
document.getElementsByTagName('head')[0].appendChild(styleNode);
innerHTML
const style = document.createElement('style');
style.innerHTML = `
#target {
color: blueviolet;
}
`;
document.head.appendChild(style);
style.sheet.insertRule
const style = document.createElement('style');
style.sheet.insertRule('#target {color: darkseagreen}');
document.head.appendChild(style);
CSSStyleSheet
// Create our shared stylesheet:
const sheet = new CSSStyleSheet();
sheet.replaceSync('#target {color: darkseagreen}');
// Apply the stylesheet to a document:
document.adoptedStyleSheets = [sheet];
https://dev.to/karataev/set-css-styles-with-javascript-3nl5
style
const div = document.createElement('div');
div.style.color = "red";
document.head.appendChild(style);
setAttribute
https://www.w3schools.com/JSREF/met_element_setattribute.asp
const div = document.createElement('div');
div.setAttribute(`style`, `color: red;`)
document.head.appendChild(style);