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?
-
possible duplicate of Is it possible to alter a CSS stylesheet using JavaScript? (NOT the style of an object, but the stylesheet itself)Quentin– Quentin2013-03-19 07:45:42 +00:00Commented Mar 19, 2013 at 7:45
-
Possible duplicate: jQuery create CSS rule / class @ runtimeBoaz– Boaz2013-03-19 07:45:56 +00:00Commented Mar 19, 2013 at 7:45
-
1Yes 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– Beetroot-Beetroot2013-03-19 07:53:11 +00:00Commented 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.MaiaVictor– MaiaVictor2013-03-19 08:03:29 +00:00Commented Mar 19, 2013 at 8:03
Add a comment
|
3 Answers
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);
5 Comments
MaiaVictor
Well there are two right answers... chosing by Math.random().
vastlysuperiorman
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.
CraZ
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
Why there's that IF?
spaceman12
IF for browsers testing for the support of dynamic stylesheet, old IE in particular...
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
MaiaVictor
Well there are two right answers... chosing by Math.random().
Mr. Smit
multiline styles: let styles = `your styles here multiline`; and then: var styletag = $(styles);