Code
function updtStyle(selector, cssRules) {
var styleSheet = null;
for (var i = 0; i < document.styleSheets.length; i++) {
if (!document.styleSheets[i].href) {
styleSheet = document.styleSheets[i];
break;
}
}
if (!styleSheet)
document.head.appendChild(document.createElement("style"));
for (var i = 0; i < document.styleSheets.length; i++) {
if (!document.styleSheets[i].href) {
styleSheet = document.styleSheets[i];
var cssRule = null;
for (var j = 0; j < styleSheet.cssRules.length; j++) {
cssRule = styleSheet.cssRules[j];
Object.keys(cssRules).map(function(k) {
cssRule.style[k] = cssRules[k];
});
break;
}
if (!cssRule) {
var newRuleText = Object.keys(cssRules).map(function(k) {
return k + ": " + cssRules[k];
}).join("; ");
styleSheet.insertRule(selector + " { " + newRuleText + "}", styleSheet.cssRules.length);
}
break;
}
}
}
Usage
updtStyle("#div:hover", { background: "rgba(255,255,255,.5)", "text-decoration": "underline" });
References
- https://stackoverflow.com/questions/7330355/javascript-set-css-after-styles/7330454#7330454
- https://davidwalsh.name/add-rules-stylesheets