JS

Assignment to read-only properties is not allowed in strict mode

Reading time of 230 words
1 minute
Reading time of 230 words ~ 1 minute


Did you find this article helpful?
Please consider tipping me a coffee as a thank you.
Ko-fi Buy Me a Coffee
Did you find this article helpful? Please consider tipping me a coffee or three as a thank you.
Tip using Ko-fi or Buy Me a Coffee

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.

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

Written by Ben Garrett

Did you find this article helpful?
Please consider tipping me a coffee as a thank you.
Ko-fi Buy Me a Coffee
Did you find this article helpful? Please consider tipping me a coffee or three as a thank you.
Tip using Ko-fi or Buy Me a Coffee