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?
3
Answers
Change the
src
, notInnerHTML.src
. You can see the answer in this question.and you need to set the
width
height
with styleYou’ve syntax errors in your code.
Try this
To set the
src
attribute of an image usinggetElementById
, you need to concatenate the string properly and then assign it to thesrc
attribute. Here’s how you can do it:In this code:
i
is your variable containing the image number.imagePath
is constructed by concatenatingi
with the rest of the path to form the full path to your image file.document.getElementById("myImg").src
is then set toimagePath
.Remember, you don’t need to set the
width
andheight
attributes viainnerHTML
. Instead, you can directly set them using thewidth
andheight
properties of the image element.Also, make sure that your
img
tag with the id "myImg" is present in your HTML markup. For example:This way, the JavaScript code will find the element with the id "myImg" and update its
src
,width
, andheight
properties.