I want to create an stylesheet like this:
var sheet = document.createElement('style'); sheet.type = 'text/css';
sheet.innerHTML = data.style;
But it seems that IE needs its own syntax. To simplify this answer's code, I have tried
var sheet = document.createElement('style'); sheet.type = 'text/css';
(sheet.styleSheet ? sheet.styleSheet.cssText : sheet.innerHTML) = data.style;
But that throws ReferenceError: invalid assignment left-hand side
.
Then, must I use...
var sheet = document.createElement('style'); sheet.type = 'text/css';
if(sheet.styleSheet) sheet.styleSheet.cssText = data.style;
else sheet.innerHTML = data.style;
... or is there a simpler alternative?
You can always do :
sheet.styleSheet ? sheet.styleSheet.cssText = data.style
: sheet.appendChild(document.createTextNode(data.style));
FIDDLE
Here's the solution which won't leave future maintainers wondering what on earth the code does:
function setSheetContent( sheet, text ) {
if(sheet.styleSheet)
sheet.styleSheet.cssText = text;
else
sheet.innerHTML = text;
}
var sheet = document.createElement('style');
sheet.type = 'text/css';
setSheetContent( sheet, data.style );
or wrap it up for even more convenience (if you never want to change the content of an existing sheet)
function stylesheetWithContent( sheet, text ) {
var sheet = document.createElement('style');
sheet.type = 'text/css';
if(sheet.styleSheet)
sheet.styleSheet.cssText = text;
else
sheet.innerHTML = text;
return sheet;
}
var sheet = stylesheetWithContent( data.style );
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With