Setting a variable in html to use as image src

I would like to know. Is it possible to set a variable in html and use that variable as the img src. I would be using the same image regularly and don't want to update it in ever tag each time I change it. I am new to Javascript and HTML.

I have tried this but knew it would not work. But tried it anyway.

<body> <var a1>images/wildlife/dog.jpg</var> <img src="var a1"> </body> 

The image path is correct as it displays the image if i use that exact path as the src="..."

Can some please point me in the direction to accomplish this. I do not know alot about php and MySql.

3

5 Answers

This would be possible with plain CSS, using CSS variables and the CSS content attribute.

:root { --a1: url('); } img { content: var(--a1); }
<img width="200" height="300" />

Browser compatibility:

0

There are no variables in HTML as stated in comments. Here's how you could this in javascript.

const a1 = "images/wildlife/dog.jpg"; const image = document.getElementById("event-1"); image.src = a1;
<img src="">
0

First set id for the image tag

then use JavaScript and set the src of image

 const a1 = ' const image = document.getElementById("image"); image.src = a1;
<!DOCTYPE html> <html> <body> <img src="" height="150px" width ="150px"> </body> </html>
0

You can achieve that with some JavaScript code

  1. Assign an id to the image tag - #img1

  2. Write your JavaScript code that would execute immediately your website loads ----------

    window.onload = Window_OnLoad; function Window_OnLoad () { }

  3. Inside the function in STEP 2 (Window_OnLoad), declare a variable and assign your image source to it ----------

    const imgSrc = "imgpath.png"

  4. Now call get the img id in STEP 1 and assign the path to it like---------

    document.getElementById("img1").src = imgSrc

You can assign the variable, imgSrc to different image tags. When you have to change it, you can change only the variable value. That should do it

Maybe this is another answer to your question. All img with "event-id" will get the same .jpg file applied to it stated in var

<!DOCTYPE html> <html> <body> <var>images/wildlife/dog.jpg</var> <img src=""></img> <script type="text/javascript"> (function () { var path = document.getElementById("path").innerHTML; document.getElementById("event-1").src = path; })(); </script> </body> </html>

Your Answer

Sign up or log in

Sign up using Google Sign up using Facebook Sign up using Email and Password

Post as a guest

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

You Might Also Like