CSS injection code outputs "Expected an assignment or function call" in Tampermonkey

The following code that works fine and uses me to inject 2 or more CSS rows via a console/script, outputs the following error in Tampermonkey (where I run it):

Expected an assignment or function call and instead saw expression

let myCss =`
    .myclass1 {/*CSS CODE*/}
    .myclass2 {/*CSS CODE*/}
`;

style = document.createElement("style");
style.type = "text/css";
style.styleSheet ? style.styleSheet.cssText = myCss : style.appendChild(document.createTextNode(myCss));

head = document.head || document.getElementsByTagName("head")[0];
head.appendChild(style);

As a JS freshman I want to share that this is the first time I encounter a case when a code outputs an error in a syntax checker, but also works.

Please check it in another syntax checker you have (I have none other - Notepad++ or Visual Studio code doesn’t offer me syntax checker, at lease not naturally).

Given the code itself work fine, I want to ask, why is this error outputted?

I had one of these a few years ago that took me the good part of an hour to solve after my cat stepped on a key.

— the back-ticks ` after the equal and before the semicolon ? :eyes:

1 Like

@Mittineague, I’m not sure I understand: Deleting the whole let myCss segment (with the backticks, equal sign and semicolon), makes no change.

Hmm, maybe it doesn’t like the ternary?
Try expanding it to this

if(style.styleSheet){ 
  style.styleSheet.cssText = myCss; 
} else { 
  style.appendChild(document.createTextNode(myCss)); 
}
2 Likes

Exactly, that was it… Hmm, surprising!

1 Like

Thanks,

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.