Is there a way to set the CSS of global classes using JavaScript or jQuery? That is, append .my_class { foo:bar }
to the <style/>
tag of the page?
Define global CSS classes using JavaScript or jQuery?
possible duplicate of Is it possible to alter a CSS stylesheet using JavaScript? (NOT the style of an object, but the stylesheet itself) –
Lase
Possible duplicate: jQuery create CSS rule / class @ runtime –
Sopping
Yes but put a large warning in your site's source, alerting anyone who works on the site in the future. In my experinece, sites with dynamically built/amended stylesheets are the most confusing things in the known universe. –
Bolero
Sorry, I knew this would most likely be a duplicate question but I've spent a few minutes searching it yesterday and could only find irrelevant links - mostly because the results were overshadowed by info about jQuery's .addClass. –
Vidda
Pure javascript -
var style=document.createElement('style');
style.type='text/css';
if(style.styleSheet){
style.styleSheet.cssText='your css styles';
}else{
style.appendChild(document.createTextNode('your css styles'));
}
document.getElementsByTagName('head')[0].appendChild(style);
Well there are two right answers... chosing by Math.random(). –
Vidda
While both answers provide a correct solution for the given question, I prefer to use pure javascript for performance reasons whenever I'm not trying to support old IE versions. –
Methylene
I'm adding the global CSS as soon as possible so that new elements are rendered respecting that new CSS. At this time, jQuery is not loaded yet and therefore pure JS is better option –
Doublecross
Why there's that IF? –
Doublecross
IF for browsers testing for the support of dynamic stylesheet, old IE in particular... –
Eichelberger
Yes, you can do that in jQuery:
var styleTag = $('<style>.my_class { foo: bar; }</style>')
$('html > head').append(styleTag);
It works by simply appending <style>
tag at the end of <head>
.
Well there are two right answers... chosing by Math.random(). –
Vidda
multiline styles: let styles = `your styles here multiline`; and then: var styletag = $(styles); –
Doll
This seems to be the way in 2023:
const sheet = new CSSStyleSheet()
sheet.replaceSync('div {padding: 2px;}')
document.adoptedStyleSheets = [sheet]
Add more styles to existing sheet:
let index = sheet.cssRules.length
sheet.insertRule('span {color: red;}', index)
© 2022 - 2025 — McMap. All rights reserved.