MaiaVictor
MaiaVictor

Reputation: 53077

Define global CSS classes using JavaScript or jQuery?

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?

Upvotes: 30

Views: 19510

Answers (3)

asdf
asdf

Reputation: 1042

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)

Upvotes: 7

spaceman12
spaceman12

Reputation: 1109

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);

Upvotes: 45

kamituel
kamituel

Reputation: 35970

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

Upvotes: 27

Related Questions