1

I want to loop through images in a subfolder named images. The purpose is to append them to an image bar in my html .

The solution I came up with was to pull out the images form the subfolder and put them in an array

const imgArray= ['pic1.jpg', 'pic2.jpg', 'pic3.jpg' , 'pic4.jpg', 'pic5.jpg']; 

and then loop through the array

for (let i = 0; i <= imgArray.length-1; i += 1) {

const newImage = document.createElement('img');
newImage.setAttribute('src', imgArray[i] ) ;
imageBar.appendChild(newImage);}

Is there a way to set a variable as the path to the image folder and then just loop through the folder. Maybe something like:

for ( let i=0;   i<= imageFolder.length -1;   i++){
const newImage = document.createElement('img');
newImage.setAttribute('src', imgFolder[i] ) ;
thumbBar.appendChild(newImage)}
1
  • 1
    You can't read the content of a folder like that. Commented Jan 2, 2021 at 17:34

1 Answer 1

2

You are correct to put the file names into an array as JavaScript does not have direct access to the file system for reading its contents.

See comments below:

// You can loop through an array directly by calling .forEach() on it
['pic1.jpg', 'pic2.jpg', 'pic3.jpg' , 'pic4.jpg', 'pic5.jpg'].forEach(function(img){
  const newImage = document.createElement('img');
  newImage.src = "images/" + img; // Just concatenate the path to the file name
  newImage.setAttribute("alt", "Some ALT text"); // images require an ALT attribute to be valid
  thumbBar.appendChild(newImage);
});

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

Comments

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.