Skip to content

Instantly share code, notes, and snippets.

@VFDan
Created July 21, 2019 00:04
Show Gist options
  • Save VFDan/35588c662a341793aaef3c22759c6e9a to your computer and use it in GitHub Desktop.
Save VFDan/35588c662a341793aaef3c22759c6e9a to your computer and use it in GitHub Desktop.
Add CSS styles with JS
function addCSS(a,b,c){b.match(/-/)&&(b=b.replace(/-([a-z])/g,function(a){return a[1].toUpperCase()}));for(var d=document.querySelectorAll(a),e=d.length,f=0;f<e;f++)d[f].style[b]=c}function addCSSRules(a){var b,c=document.createElement("style");document.head.appendChild(c),b=c.sheet;for(var d=0,e=a.length;d<e;d++){var f=1,g=a[d],h=a[d][0],k="";"[object Array]"===Object.prototype.toString.call(g[1][0])&&(g=g[1],f=0);for(var l,m=g.length;f<m;f++)l=g[f],k+=l[0]+":"+l[1]+(l[2]?" !important":"")+";\n";b.insertRule(h+"{"+k+"}",b.cssRules.length)}}!function(a){var b=a.insertRule;2===b.length&&(a.insertRule=function(c){t:for(var d=0,f=c.length,g=0,h=0;d!==f;++d){if(h=c.charCodeAt(d),!g&&123===h){for(var j=d,a=-1;d!==f;++d)h=c.charCodeAt(d),g||125!==h||(a=d),g^=92===h?1:g;if(-1==a)break t;return b.call(this,c.substring(0,j),c.substring(a),arguments[3])}g^=92===h?1:g}return b.call(this,c,"",arguments[2])})}(CSSStyleSheet.prototype);
/* How to use:
* addCSS(selector, property, value)
* * addCSS('div:first-of-type', 'color', 'red');
* addCSSRules(rules)
* * addCSSRules([
[ "span", [
["color", "white"],
["background-color", "blue"]
]],
[ "span.bi", [
["font-weight", "bold"],
["font-style", "italic"]
]]
])
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment