30

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?

4
  • possible duplicate of Is it possible to alter a CSS stylesheet using JavaScript? (NOT the style of an object, but the stylesheet itself) Commented Mar 19, 2013 at 7:45
  • Possible duplicate: jQuery create CSS rule / class @ runtime Commented Mar 19, 2013 at 7: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. Commented Mar 19, 2013 at 7: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. Commented Mar 19, 2013 at 8:03

3 Answers 3

45

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);
Sign up to request clarification or add additional context in comments.

5 Comments

Well there are two right answers... chosing by Math.random().
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.
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
Why there's that IF?
IF for browsers testing for the support of dynamic stylesheet, old IE in particular...
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>.

2 Comments

Well there are two right answers... chosing by Math.random().
multiline styles: let styles = `your styles here multiline`; and then: var styletag = $(styles);
7

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)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.