Search code examples
javascriptgetelementbyid

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


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?


Solution

  • 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";