Invalid assignment of the left side with triple if

I want to create a stylesheet as follows:

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 , I 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, I have to 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?

+6
source share
2 answers

You can always do:

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

Fiddle

+3
source

Here's a solution that will not be left to future maintainers, asks what the code actually 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 for even more convenience (if you never want to modify the contents 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 ); 
+1
source

Source: https://habr.com/ru/post/951003/


All Articles