Server

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


Using JavaScript to apply CSS to Internet Explorer/Edge returns ‘Assignment to read-only properties is not allowed in strict mode’

I encounted a silly mistake on my behalf the other day when programming some JavaScript DOM. This simple JS code to apply a style to a 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 actually .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 does 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 adhearing to the ECMAScript5 standard while Firefox and Chrome continue to allow a quirks, strict mode for code compatibility.

Example code: https://github.com/bengarrett/devtidbits.com/tree/master/post_3622

Advertisements

Leave a Reply

Please log in using one of these methods to post your comment:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s