8

Given:

body = document.getElementsByTagName('body')[0];
iframe = document.createElement('iframe');
iframe.src = protocol + settings.scriptUrl + a;
iframe.height = 1;
iframe.width = 1;
iframe.scrolling = 'no';
iframe.frameborder = 0;
iframe.style = 'display:none';
body.appendChild(iframe);

I see TypeError: Attempted to assign to readonly property. on the iframe.style = line when testing in Safari, using strict mode.

While it might make sense to require a setter or similar for .style, I can't seem to find any information about this being a requirement, and I can also can't find a recommendation for what I should be doing instead.

Some searching lead me to CSSStyleDeclaration.setProperty(), which may be what I want, but I'm not sure. And even if that's the right thing to do, I still haven't found any information on either which browsers support this; or how to make sure it works both with/without strict mode and in new/old browsers.

2
  • Try iframe.style.display = "none";
    – Florian Gl
    Jul 23, 2014 at 9:06
  • 1
    Do not set inline styles at all. Assign a class name and style that one; e.g. iframe.classList.add('hidden'); and CSS .hidden { display: none; }. This will save you some trouble in the long way.
    – feeela
    Jul 23, 2014 at 9:07

1 Answer 1

17

If you are taking that approach, you need to edit element.style.cssText not element.style.

From Mozillas documentation:

Styles can not be set by assigning a string to the (read only) style property, as in elt.style = "color: blue;". This is because the style attribute returns a CSSStyleDeclaration object.

Note that overwriting it will overwrite all the existing inline styles on the element, so you'll generally want to set element.style.display = "none"; instead.

A better approach, generally, is to modify the classes to which the element belongs and have your styles defined in a separate stylesheet.

1
  • Thanks, I'll give this a try. Do you happen to have a reference explaining the behavior? I'd like to know understand in more detail the thinking around why .style is readonly. Manipulating classes would be a lot better though, that's true.
    – Letharion
    Jul 23, 2014 at 9:20

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.