Get image from JSON file using JavaScript and display in HTML img tag
html, javascript, json
Solution
Create an Image object (with needed attributes) and add it to the exiting div
var data = {
"images": [{
"bannerImg1": "https://i.stack.imgur.com/HXS1E.png?s=32&g=1"
},
{"bannerImg1" : "https://i.stack.imgur.com/8ywqe.png?s=32&g=1"
}]
};
data.images.forEach( function(obj) {
var img = new Image();
img.src = obj.bannerImg1;
img.setAttribute("class", "banner-img");
img.setAttribute("alt", "effy");
document.getElementById("img-container").appendChild(img);
});
<div class="banner-section" id="img-container">
</div>
Problem
I'm really unsure what I'm doing wrong here. My code makes sense to me, but then again I guess I'm just a beginner. Seems so simple yet I can't figure it out. Any help would be great, please and thank you. Please read code comments for specifications of what I'm trying to do. JSON code: ``` {"images":[ { "bannerImg1":"./images/effy.jpg" }]} ``` JavaScript: ``` $.getJSON('data.json', function(data) { // Get data from JSON file for (var i in data.images) { var output+=data.images[i].bannerImg1; // Place image in variable output } document.getElementById("banner-img").innerHTML=output;}); // Display image in the img tag placeholder ``` HTML: ``` <div class="banner-section"> <!-- Image should load within the following img tag --> <img class="banner-img" alt="effy"> </div> ```