24

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?

Ram
  • 143,282
  • 16
  • 168
  • 197
MaiaVictor
  • 51,090
  • 44
  • 144
  • 286
  • possible duplicate of [Is it possible to alter a CSS stylesheet using JavaScript? (NOT the style of an object, but the stylesheet itself)](http://stackoverflow.com/questions/6620393/is-it-possible-to-alter-a-css-stylesheet-using-javascript-not-the-style-of-an) – Quentin Mar 19 '13 at 07:45
  • Possible duplicate: [jQuery create CSS rule / class @ runtime](http://stackoverflow.com/questions/1212500/jquery-create-css-rule-class-runtime) – Boaz Mar 19 '13 at 07:45
  • 1
    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. – Beetroot-Beetroot Mar 19 '13 at 07:53
  • 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. – MaiaVictor Mar 19 '13 at 08:03

3 Answers3

39

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);
spaceman12
  • 1,039
  • 11
  • 18
  • 3
    Well there are two right answers... chosing by Math.random(). – MaiaVictor Mar 19 '13 at 08:14
  • 3
    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. – vastlysuperiorman Sep 29 '15 at 21:45
  • 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 – CraZ Apr 24 '20 at 10:02
  • Why there's that IF? – CraZ Apr 24 '20 at 10:06
  • IF for browsers testing for the support of dynamic stylesheet, old IE in particular... – spaceman12 Apr 25 '20 at 13:26
27

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>.

kamituel
  • 34,606
  • 6
  • 81
  • 98
0

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)
asdf
  • 952
  • 14
  • 13