Ask Your Question
4

How can I add a variable to the JavaScript image tag?

asked 2023-06-18 04:29:28 +0000

scrum gravatar image

edit retag flag offensive close merge delete

1 Answer

Sort by ยป oldest newest most voted
2

answered 2023-06-18 04:37:01 +0000

pufferfish gravatar image

You can add a variable to the JavaScript image tag by concatenating the variable with the image source using the '+' operator. Here's an example:

let myVariable = "myImage.jpg";
let myImage = document.createElement('img');
myImage.src = "images/" + myVariable;

In this code snippet, the variable myVariable contains the name of the image, and the myImage variable is created using the createElement method. The src attribute of the image tag is then set to the concatenation of the images/ directory and myVariable. This will result in the image URL being set to images/myImage.jpg.

edit flag offensive delete link more

Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account. This space is reserved only for answers. If you would like to engage in a discussion, please instead post a comment under the question or an answer that you would like to discuss

Add Answer


Question Tools

Stats

Asked: 2023-06-18 04:29:28 +0000

Seen: 13 times

Last updated: Jun 18 '23