"); document.write(" "); document.write(" "); document.write("

How can I write the content of a variable in image src while using document.getElementById?

62 Views Asked by At

I have the following code

document.write("<img src=./", i, ".png width='100px' height='100px'>");
document.write("<img src=./", x, ".png width='100px' height='100px'>");
document.write("<img src=./", y, ".png width='100px' height='100px'>");`

and I want to use the src in getElementById(myImg).InnerHTML.

I tried this

document.getElementById("myImg").innerHTML.src = "./", i, ".png width='100px' height='100px'>";

But It's not working

What is the proper way to write it?

2

There are 2 best solutions below

0
Aminarune On BEST ANSWER

Change the src, not InnerHTML.src. You can see the answer in this question. and you need to set the width height with style

document.getElementById("myImg").src=`./${i}.png`;
document.getElementById("myImg").style.width="100px";
document.getElementById("myImg").style.height="100px";
0
Siddiqui Affan On

You've syntax errors in your code.

Try this

const img = document.getElementById("myImg");
const i = 'some_string_or_number'
 
img.src = "./"+i+".png";
img.width='100px';
img.height='100px';