Using JavaScript to apply CSS to Internet Explorer/Edge returns ‘Assignment to read-only properties is not allowed in strict mode’
I encountered a silly mistake on my behalf the other day when programming some JavaScript DOM. This simple JS code to apply a style to an HTML element works fine in Chrome and Firefox. But breaks in Microsoft’s Edge and Internet Explorer with the following error.
Assignment to read-only properties is not allowed in strict mode
"use strict"; function blueText() { var txt = document.getElementById("text"); txt.style = "color: blue"; }
The solution is to use the correct property to apply the CSS, which is .style.cssText
So the following will function work in all browsers.
"use strict"; function blueText() { var txt = document.getElementById("text"); txt.style.cssText = "color: blue"; }
But why do Chrome and Firefox allow for my lazy programming and Microsoft browser’s do not? Well, the Mozilla Developer Network has the answer.
Note that styles should NOT be set by assigning a string directly to the style property (as in elt.style = “color: blue;” ), since it is considered read-only (even though Firefox(Gecko), Chrome and Opera allow it) because the style attribute returns a CSSStyleDeclaration object which is also read-only.
https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/style
In this case, it is Microsoft that is adhering to the ECMAScript5 standard while Firefox and Chrome continue to allow a strict quirks mode for code compatibility.
Example code: https://github.com/bengarrett/devtidbits.com/tree/master/post_3622
Colloquialism is quite popluar for writers – kudo’s to Chrome, Firefox and Opera for doing the same with their code. Microsoft is still the exception here. IMO when you see a popular deviation from the ‘technically correct’ way to do something that often implies the the correct way wasn’t designed well.
Great article!