0

I need to display about 20 images in my web app and they all in the content folder

I don't what to write <img src='content/image_name.png'> for every image in HTML

is there is a way to loop through all images in one folder with only java Script?

i expect something like:

folder = //i don't know what to write 
const body = document.body
folder.forEach(file => {
    const photo = document.createElement('img')
    photo.setAttribute('src',`content/${file}` )
    body.append(photo)
})

I did something like that in python using os.listdir() but i don't whon how to do it with js

1
  • Unless you know the names of the files in that folder, then it is not possible Commented Apr 9, 2021 at 12:54

1 Answer 1

1

You need to provide javascript with some information about the files; this usually works through some sort of backend api call.

There are many ways to do the api call, but ideally it should provide a list of filenames which javascript can then write as the img src value in the loop

To do the loop:

// Verbose naming is for clarity in this answer so that you
// can understand what the code is doing.
const imagePathsFromApi = doApiCallToGetImagePaths();

const body = document.querySelector("body");
for (let i = 0; i <= imagePathsFromApi.length; i++)
{
    let imgTag = `<img src="${imagePathsFromApi[i]}" alt="..." />`;
    body.innerHTML += imgTag;
}

You could also use a forEach loop:

imagePathsFromApi.forEach(value, index)
{
    let imgTag = `<img src="${value}" alt="..." />`;
    body.innerHTML += imgTag;
}

Either way you need to set up some kind of API that'll get the image data from the folder in some way since javascript isn't capable of reading that information.

Sign up to request clarification or add additional context in comments.

1 Comment

Hi @ortund, could you provide an example of such API and how to use it? I don't know why this is working: <img alt="robot" src={https://robohash.org/${id}?300*300} /> but this is not working: <img src={/Images/${id}.png} height='300' alt='robots' />. Even as my Images folder is in my public directory. I want to map each ID to a one image

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.