skip to Main Content

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


  1. 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";
    
    Login or Signup to reply.
  2. 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';
    
    Login or Signup to reply.
  3. To set the src attribute of an image using getElementById, you need to concatenate the string properly and then assign it to the src attribute. Here’s how you can do it:

    // Assuming you have an image element with the id "myImg"
    var i = 1; // Example value for i
    var imagePath = "./" + i + ".png";
    document.getElementById("myImg").src = imagePath;
    document.getElementById("myImg").width = "100px";
    document.getElementById("myImg").height = "100px";
    

    In this code:

    • i is your variable containing the image number.
    • imagePath is constructed by concatenating i with the rest of the path to form the full path to your image file.
    • document.getElementById("myImg").src is then set to imagePath.

    Remember, you don’t need to set the width and height attributes via innerHTML. Instead, you can directly set them using the width and height properties of the image element.

    Also, make sure that your img tag with the id "myImg" is present in your HTML markup. For example:

    <img id="myImg" src="" alt="My Image">
    

    This way, the JavaScript code will find the element with the id "myImg" and update its src, width, and height properties.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search