Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Invalid assignment left-hand side with ternary if

Tags:

javascript

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?

like image 981
Oriol Avatar asked Aug 04 '13 20:08

Oriol


2 Answers

You can always do :

sheet.styleSheet ? sheet.styleSheet.cssText = data.style 
                 : sheet.appendChild(document.createTextNode(data.style));

FIDDLE

like image 200
adeneo Avatar answered Sep 17 '22 11:09

adeneo


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 );
like image 44
Dave Avatar answered Sep 20 '22 11:09

Dave