Is there a way to loop through an image within a javascript file, and then uploading it to the html and css file?
I’m trying to make a image gallery. I find it tiring and inefficient to set a background-image for each one of my div. Is there a way to use javascript to loop through images and then upload it back to my HTML and CSS?
Any help is appreciated, thanks
Hey there @revenstar2
,
I don’t think you can really loop through a full blown image, but what you can do is loop through the images’s file path. Then just use some simple HTML to display it.
What you can also do is put a lot of images, and hide them. Then use JS to go through them.
Just giving ideas… 
Hope this helps.
Right that was what I was going for, but then how do I get it to loop around the html and css files
Let’s say I have 9 div and then an array with 9 pictures
how do I get the array to loop and insert the pictures to the div according to its index? Is it even possible?
Hi,
You can do like this. Let’ say
- In one folder, you will have images named like this --> img01.jpg , img02.jpg…img09.jpg.
- You have one div with img tag in it.
- This img tag will have a default path for any one img let’s say img01.jpg
- Using DOM manipulation, you can just loop through each image name for just that particular img tag’s src.
example -->
<img id="img-loop" src="images/img01.jpg" alt="imgs-alt"/>
.......... some other code .....
<script>
DOM logic // make sure this script should be called at the end of the page before body closing tag
</script>
</body>
hope this helps,
Abhishek
1 Like
Thanks, but what if I wanted to use the loops to give different images to different div? Is it possible? Though I will use the method you gave since it’s useful
If you wanted to loop through images for different div’s then i suggest you to add each img tag an id=“img-loop-01”
for each img tag, change the id number like img-loop-02, img-loop-03…09.
try a for loop to change img src=“images/img01.jpg” where id is img-loop-01…and so on for 9 times.
OR
You can do it in a different way as well. You can just change the background for each div to an image URL. just make sure to put some height to it otherwise you won’t see it if there is no content in the div.
I don’t know the idea behind doing this but something can definitely be implemented.
Hope this helps,
Abhishek
1 Like
Thanks mate, I will try to just change each div background as tedious at it maybe. Just praying my website load speed would go at a snail pace
Good luck & Happy coding mate !
regards,
Abhishek.
1 Like