Setting the variable to global does not apply styling to the element

Looking for help with styling an element created using document.createElement("img")?

let fireball; //global variable

fireball = document.createElement("img") //variable on local
fireballArray.push(someFunction(fireball, {
 src: "img.png", width: "38" }))

fireball.style.display = "none" //global variable

I want to style the element created by

fireball = document.createElement("img")
, but it's not hiding as expected.

Any suggestions or solutions would be greatly appreciated. Thank you in advance!

Note: The variable

fireball = document.createElement("img")
must remain within local scope while styling should be applied from another scope (as shown in the code).

Answer №1

When you are creating your image dynamically:

function createImage() {
  var fireball = document.createElement("img");
  fireball.setAttribute("src", "img_pulpit.jpg");
  fireball.setAttribute("width", "304");
  fireball.setAttribute("height", "228");
  fireball.setAttribute("alt", "The Pulpit Rock");
  fireball.setAttribute("id", "UniqId"); // Remember to give it a unique ID
  document.body.appendChild(fireball);
}

To manipulate the element, use getElementById:

function manipulateImage() {
  var fireball = document.getElementById("UniqId");
  fireball.setAttribute("style", "display:none; border:3px solid red;");
  document.body.appendChild(fireball);
}

You can try this out with the w3C demo here : https://www.w3schools.com/jsref/tryit.asp?filename=tryjsref_img_create

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

When running the command `npm install <node_module> --save`, the dependencies are not being updated as

<=== If you're facing the same issue, try reinstalling your computer to fix it ===> I recently had to reformat my computer and set everything up again. After reinstalling Node and NPM, I encountered some problems that are really irritating me. ...

Incorporating an element into a nested array

I have an array stored in a variable called 'items' with various products and their attributes. I am looking to randomly generate a popularity score between 1 and 100 for the items that currently do not have one. This is my current array: const ...

Space between an image and a div element

While creating a website in Dreamweaver CC, I noticed a significant gap between my image and a div tag. Here is a screenshot for reference: Below is the code from my index file: <!doctype html> <html> ... </div> Additionally, here is a ...

What alternative methods are available to rename a field that has been returned in mongoose, if at all possible?

I need help with this specific query: MessageModel.find({ conversationId: { $in: ids } }) .sort({createdAt: 'ascending'}) .populate({ path: 'receiver', select: '_id' }) .populate({ path: &a ...

Is it permissible to access an iframe directly by its name?

I recently came across some JavaScript code that directly accesses an iframe by its name, without using getElementById() or any other method. Surprisingly, this code seems to be functioning properly in browsers like Chrome, Firefox, IE10, and Safari for Wi ...

After installing grunt, the Gruntfile cannot be located. How can this issue be resolved?

After installing grunt, I encountered a problem. Despite trying some commands suggested on stackoverflow in this How to install grunt and how to build script with it, running the grunt command still shows the same result. What steps should I take next?ht ...

What is the process for redirecting an API response to Next.js 13?

Previously, I successfully piped the response of another API call to a Next.js API response like this: export default async function (req, res) { // prevent same site/ obfuscate original API // some logic here fetch(req.body.url).then(r => ...

You cannot assign a promise to a React state

Calling a function from MoviesPage.tsx to fetch movie data results in a promise containing an object that is successfully fetched (can confirm by console logging). However, I'm facing an issue when trying to assign the result to a state - receiving a ...

When clicked, elevate the element to the top of the window with an offset

Is there a way to click on this button, which is located within an accordion section header, and have it automatically move to the top of the page based on the window size? It seems like it should be a simple task, but sometimes after a long day things ca ...

Ways to align a button in the center using Material-UI

I'm struggling to find a way to center buttons in Material-UI. Here is the code snippet I currently have: function BigCard(props) { const { classes } = props; return ( <div> <Card className={classes.card}> <C ...

Guide on Deleting Specific Item Using SQL Data Source Delete Statement

I am facing an issue when trying to remove a specific item from a grid view in my SQL server database. I have configured DataKeyNames and linked a sql data source with the grid view. The delete command is set as follows: DeleteCommand="DELETE FROM product ...

Is there a way for me to intercept JavaScript code before it runs on Chrome?

Looking to develop a Chrome extension for the developer tools that can intercept JavaScript code on a current web page prior to compilation or execution by the browser. I aim to instrument the JS code before it runs in the browser. Could someone assist wi ...

Issue with Dismiss Button Display in Bootstrap Alert

I've been experimenting with Bootstrap and I realized that even though I followed all the instructions on their Alert page, my close button just appears as a large grey square with an X in it. Any suggestions on what might be missing? https://codepe ...

Conceal specific pages within the DataTable without deleting them

Currently, I am facing an issue where the dataTable paginates and removes the DOM pages along with the data. My goal is to extract all the data from the dataTable and convert it to JSON without losing access to the DOM when pagination occurs. I want to m ...

Retrieving the selected date from mat-datepicker into a FormControl

When creating a POST request to an API, I encountered an issue with the mat-datepicker field as it throws an error when inside the ngOnInit() call (since nothing is selected yet). Other fields like name, email, etc. work fine, but extracting a value from t ...

The Contact.php page has the ability to send emails, however, the content of the

I have recently added a contact form to my website using a template. Although I am able to send and receive email messages successfully, I am facing an issue where the actual message content entered by users is not being received in my Inbox. Here is a sc ...

What is the best way to pass an array of 8-digit strings from an input in Angular to a Node.js backend?

I am currently facing a challenge where I need to pass an array of 8 digit strings from an Angular input to a Node.js endpoint. The method below works perfectly fine when passing a single string, but how can I handle an array of 8 digit strings as input? ...

Error encountered when attempting to retrieve data from a JSON object

I'm in the process of extracting some information from a JSON object, but I've encountered a confusing issue. The JSON object structure is as follows: { "status": "success", "data": { "image": null, "video": null, "author": null, "publisher": "M ...

Triggering a modal window with unique content by clicking on various images

Is there a way to trigger a modal window through clicking on an image? Additionally, can different images open different content upon clicking? I am planning to showcase a portfolio where clicking on an image will activate a modal that displays other image ...

The Vue2 @click event does not function properly when using v-html within a different component

I currently have a sign up form that includes an Alert component for displaying any errors. One of the conditions may prompt a message saying "You already have an account, click here to log in". The error messages are passed as props to the "Alert" compon ...