I would like to add an image to a website using a javascript array. I found a code and then I tried to change it. But i can't get it to work. My code does not display the image on the site.
Code I found:
const imageOut = document.querySelector('.image-out');
for (let key in images) {
let img = document.createElement('img');
img.setAttribute('data-key', key);
img.src = 'images/' + key + '.png';
imageOut.append(img);
}
html tag: <div class="image-out"></div>
Array:
const images = {"JD-03-128" :{},"JD-05-128": {},"JD-07-128": {},"JD-11-128": {},"JD-12-128": {},"JD-13-128": {},"JD-15-128": {}};
My code:
var imageOut = document.querySelector(".image-out");
for (let key in a) {
let img = document.createElement('img');
img.setAttribute('data-key', key);
img.src = 'image/'+key+'.jpg';
imageOut.append(img);
}
html tag: <div class="image-out"></div>
Array:
const a = {"a":{},"b":{},"c":{},"d":{},"e":{},"f":{},"g":{}};
image my code: jpg, name absolutely match, name folder absolutely match with folder in my code. where is my problem ?
If you want to append (add) multiple images to an HTML document using an array, then you can do something like below.
const rootElement = document.getElementById('root')
const array = [
'https://picsum.photos/id/237/200/300',
'https://picsum.photos/id/238/200/300',
'https://picsum.photos/id/239/200/300'
]
array.forEach((src) => {
const imageElement = document.createElement('img')
imageElement.src = src
rootElement.appendChild(imageElement)
})
img{margin:5px}
<div id='root'></div>
So basically I'm creating an <img src='' /> element for every item in the array. The items in the array are the url (src) of the images. Those are added as an attribute to the imageElement like so imageElement.src = src and finally they are appended as a child of rootElement