/**
* Add a stylesheet rule to the document (may be better practice, however,
* to dynamically change classes, so style information can be kept in
* genuine styesheets (and avoid adding extra elements to the DOM))
*
* @param {Array} rules Accepts an array of JSON-encoded declarations
* @example
addStylesheetRules({
'h2': {
'color': 'red',
'background-color': ['green', true] // 'true' for !important rules
},
'.myClass': {
'background-color': 'yellow'
}
});
*/
function addStylesheetRules (rules) {
var styleEl = document.createElement('style');
document.head.appendChild(styleEl);
// Apparently some version of Safari needs the following line? I dunno.
styleEl.appendChild(document.createTextNode(''));
var s = styleEl.sheet;
for(var selector in rules) {
var props = rules[selector];
var propStr = '';
for(var propName in props) {
var propVal = props[propName];
var propImportant = '';
if(propVal[1] === true) {
// propVal is an array of value/important, rather than a string.
propVal = propVal[0];
propImportant = ' !important'
}
propStr += propName + ':' + propVal + propImportant + ';\n';
}
s.insertRule(selector + '{' + propStr + '}', s.cssRules.length);
}
}
addStylesheetRules({
'div': {
'@-webkit-keyframes': 'test'
}
});
Please Whitelist JSFiddle in your content blocker.
Help keep JSFiddle free for always by one of two ways:
Whitelist JSFiddle in your content blocker (two clicks)
Go PRO and get access to additional PRO features →
Join the 4+ million users, and keep the JSFiddle dream alive.
Ad-free
All ads in the editor and listing pages are turned completely off.
Use pre-released features
You get to try and use features (like the Palette Color Generator) months before everyone else.
Fiddle collections
Sort and categorize your Fiddles into multiple collections.
Private collections and fiddles
You can make as many Private Fiddles, and Private Collections as you wish!
Console
Debug your Fiddle with a minimal built-in JavaScript console.