Skip to content

Instantly share code, notes, and snippets.

@shadybones
Last active January 31, 2022 05:33
Show Gist options
  • Save shadybones/9816763 to your computer and use it in GitHub Desktop.
Save shadybones/9816763 to your computer and use it in GitHub Desktop.
Test a snippet of JS for dynamically creating CSS classes using JS
<html>
<head>
<style type="text/css">
.ccc{ background-color: blue; }
</style>
</head>
<body>
<script type="text/javascript">
function createClass(name,rules){
var style = document.createElement('style');
style.type = 'text/css';
document.getElementsByTagName('head')[0].appendChild(style);
if(!(style.sheet||{}).insertRule)
(style.styleSheet || style.sheet).addRule(name, rules);
else
style.sheet.insertRule(name+"{"+rules+"}",0);
}
function applyClass(name,element,doRemove){
if(typeof element.valueOf() == "string"){
element = document.getElementById(element);
}
if(!element) return;
if(doRemove){
element.className = element.className.replace(new RegExp("\\b"+name+"\\b","g"),"");
}else{
element.className = element.className + " "+name;
}
}
createClass('.aaa',"background-color: green;");
</script>
<div id="bbb" class="ccc" style="width:500px;height:500px;"></div>
<a href="javascript:applyClass('aaa','bbb')">Apply class</a><br/><a href="javascript:applyClass('aaa','bbb',true)">UN-apply</a>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment