I’m trying to show an image on my webpage where the image URL comes from a JavaScript variable instead of being hardcoded in the HTML. Here’s what I have so far:
function loadContent() {
var pictureLink = "https://example.com/images/photo123.jpg";
var productTitle = "Product Title";
document.getElementById("textDisplay").innerHTML = productTitle;
}
<body onload="loadContent()">
<div class="gallery-section">
<div class="picture-container">
<img src="" id="displayImage" alt="Product Photo">
</div>
</div>
</body>
The problem is that my img element has an empty src attribute, but I need it to use the pictureLink variable from my JavaScript function. What’s the correct way to dynamically set the image source using the variable value? I can successfully update text content but I’m stuck on how to handle the image source attribute.
You’re on the right track with getElementById for the text - just do the same thing for your image. Add document.getElementById("displayImage").src = pictureLink; right after you declare pictureLink. I’ve hit this same issue tons of times building dynamic galleries, and this approach works great across browsers. Your image element already has the right id (“displayImage”), so once you drop in that line, everything should load properly when loadContent runs.
To set the image source dynamically using the variable, you need to modify your loadContent() function. After defining the pictureLink, include this line to assign the src attribute of the image element: document.getElementById("displayImage").src = pictureLink;. An alternative method would be using setAttribute, but the direct approach is more straightforward. Here’s how your updated function should look: function loadContent() { var pictureLink = “https://example.com/images/photo123.jpg”; var productTitle = “Product Title”; document.getElementById(“textDisplay”).innerHTML = productTitle; document.getElementById(“displayImage”).src = pictureLink; }. This will dynamically display the image as intended.
just grab the img element and set the src directly. add document.getElementById("displayImage").src = pictureLink; right after you set pictureLink in loadContent. done!
This topic was automatically closed 6 hours after the last reply. New replies are no longer allowed.