What is the proper way to define an element's style property in strict mode?

Assuming:


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

An error message of

TypeError: Attempted to assign to readonly property.
pops up on the line where iframe.style = is located while testing in Safari with strict mode enabled.

It seems logical to require a setter for .style, but no concrete information can be found on this requirement nor any suggestions on what should be done instead.

After some research, I stumbled upon CSSStyleDeclaration.setProperty(), which might be the solution needed. However, uncertainty remains regarding browser support, compatibility with strict mode, and variations between new and old browsers.

Answer №1

When approaching this issue, it is essential to adjust element.style.cssText rather than element.style.

Referencing the documentation from Mozilla's official guide:

You cannot set styles by assigning a string to the (read-only) style property, such as elt.style = "color: blue;". This is because the style attribute returns a CSSStyleDeclaration object.

Keep in mind that replacing it will erase all existing inline styles on the element, so it is advised to use element.style.display = "none"; instead.

A more effective strategy would be to modify the classes associated with the element and define your styles in a separate stylesheet.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

An error occurs when trying to load data into a grid upon clicking, resulting in an Uncaught TypeError: Unable to access properties of undefined (specifically 'dataState')

I have implemented a grid in React using a specific library, and I want to populate the grid with data fetched from an API call when the user clicks on a button labeled Fetch Products. However, I encounter an error during debugging: Uncaught (in promise) T ...

Obscure Promise Structure - Accomplish, Flop, Achieved

I came across the following code block and I'm struggling to understand it. While I have a good grasp on promises in the context of: deferred.then(successCb, errorCb); This code snippet appears to have three callbacks (complete, fail, done>) whic ...

Dealing with asynchronous tasks in JavaScript

I am currently delving into the world of Node development and struggling to grasp the asynchronous nature of JavaScript and Node.js. My project involves creating a microservices backend web server using Express in the gateway service, which then translates ...

Invoking an AJAX function that is not inside the document.ready function

I'm having trouble populating a Google Map and here's some of the code I'm using. The ajax request doesn't seem to be working properly. When I put everything inside document.ready() as an anonymous function, it works fine. However, sinc ...

Ways to take an item out of your shopping cart

Do you have any ideas on how to handle cart redirection in JavaScript? My specific request involves a cart with a function that removes products. What approach should I take to redirect to the main page if the cart becomes empty? Here is the delete produc ...

The Javascript countdown feature may experience issues on Safari and IE browsers

Why does this function work in Chrome, but not on IE or Safari? function countdown(){ var dDay = new Date().getUTCDate() + 1; var dMonth = new Date().getUTCMonth() + 1; var dYear = new Date().getUTCFullYear(); var BigDay = new Date(dYear+ ...

Visualizing data with a grouped bar chart in D3.js

I am currently working on creating a vertical bar chart using D3.js, similar to the one shown in this (source: statcan.gc.ca) However, I am facing an issue as I am unable to display two sets of data for comparison. Following a tutorial from , I have cr ...

Is this code in line with commonly accepted norms and standards in Javascript and HTML?

Check out this Javascript Quiz script I created: /* Jane Doe. 2022. */ var Questions = [ { Question: "What is 5+2?", Values: ["7", "9", "10", "6"], Answer: 1 }, { Question: "What is the square root of 16?", Values: ["7", "5", "4", "1"], Answer: ...

Error: The object does not contain the specified method

After deploying a web app to a remote host, I encountered an unusual error. Uncaught TypeError: Object #<error> has no method 'endsWith' Key Information: The application functions perfectly on my local machine as the host. The error ari ...

What causes the width of a card to vary between Windows and a Macbook Pro?

Here is the code I have: <div id="app"> <v-app id="inspire"> <v-content> <v-container> <v-card max-width="1000" class="mx-auto" > <v-form v-model="valid"> ...

What is the CSS code to extend the width or length of a form field?

I am working with a form field box that has the class CCPPDisplayTD. I am attempting to increase its length using CSS styling. What is the best way to achieve this using CSS? ...

The removal of an object becomes unsuccessful when objects with lower indices have been deleted beforehand

Attempting to construct a multi-layer object representing a program; check out my progress here http://codepen.io/Irish1/pen/lbjdw Imagine adding 3 weeks, each with 3 days, and each day having 3 sessions. Removing these objects is feasible as long as caut ...

When working in Javascript, make sure to replace newline and carriage return characters in strings with empty spaces. Also, don't forget to replace the literal sequences and

When working with Javascript, I am looking to perform multiple string replacements as outlined below. Remove all newlines and carriage returns Swap out instances of \n with a newline character Change occurrences of \r with a carriage return char ...

drag and drop feature paired with additional textarea below

query 1: How can I make the bottom-left textarea move together with the top-left textarea when I drag it down? query 2: What is the solution to prevent the left-bottom textarea from moving when I drag down the top-right textarea? http://jsfiddle.net/4BX6 ...

Completing the pledge using ionic/ui-routing

I've encountered an issue with my promise not resolving as expected while using Ionic/ui-routing. This is the structure of my service: return { all: function () { $localForage.getItem('foo').then(function (bar) { re ...

Encountering a problem when trying to set the value in the controller and receiving unexpected output from the console

Attempting to assign a value to an object and show it in the view, but encountering an issue. When setting the vm.order.info.when to 'Any Value' and logging the vm.order.info, the value appears correct at first glance. However, upon inspecting th ...

Can we disable hydration warnings for all nested children within a component in NextJS?

Note: I am currently using NextJS 14, but I suspect this issue also exists in NextJS 13. I have created a ThemeToggle component that utilizes the next-themes package. Even if I develop my own version of next-themes using React Context or another state man ...

Is it necessary to delay until the entire page finishes loading in Selenium 3?

public boolean CheckPageLoadStatus(){ final ExpectedCondition<Boolean> pageLoadCondition = new ExpectedCondition<Boolean>() { public Boolean apply(final WebDriver driver) { return ((JavascriptExecutor) driver).executeScr ...

Guide to activating a function by tapping anywhere on a webpage in iPhone Safari

I am attempting to implement a jQuery function that will change the text of a div in the iPhone browser when any area of the page is clicked. Here is my current setup: <div id="alternative_text">traduit</div> <script type="text/javascript ...

I'm having trouble utilizing toastify.js after installing it via npm. I keep receiving the error message "Failed to resolve module specifier." Any advice

Currently, I am attempting to utilize Toastify-js, a library designed for toast type messages, by installing it through npm. In the provided documentation, following the execution of the installation command, there is a direction that states: - To begin ...