Chema Mora Chema Mora - 5 months ago 13x
Javascript Question

Loop thru an array of images and push the content to a bootstraps placeholder in html markUp

I am trying to built a function that push each index of an array of images into a placeholder in my html. So, place the first index of the images array into the first index of the placeholders array, the second into the second, and so on.

At the moment when the code runs, the whole images array goes into every placeholder, what am I missing?

This is the JS Code =>

(function pushImages() {
//array of images, better to store in an object ?
var images = ["07750013.jpg", "07750015.jpg", "07770021.jpg", "08210019.jpg", "08220021.jpg", "08230008.jpg", "08240009.jpg", "14990007.jpg", "15000008.jpg", "15000009.jpg", "15010024.jpg", "15020018.jpg", "15020021.jpg", "15030012.jpg","15030025.jpg"];

for (var i = 0; i < images.length; i++){
//push the image to the markUp
var newImage = images[i];
var markUp = ("<img src='img/" + newImage + "' class='img-responsive'</img>");
// get bootstrap place holder where to insert.after
var placeHolder = document.getElementsByClassName("col-md-3");
for (var h = 0; h < placeHolder.length; h++) {
//insert the markUp into the html after the placeholder
placeHolder[h].insertAdjacentHTML("beforeend", markUp);

Here is the complete code from Codepen:

I am trying to built this as part of a bigger app for a pop up image Gallery slider. I could do using a Jquery plugin but I am trying learn the way to do it myself without help of external plugins and only with JS.

Any help would be appreciated. Thanks in advance.


I have changed my answer, this populates the parent container with placeholders. I haven't changed the CSS so you should make it fit but you can see the principle how to do it.


<div class="container-fluid" id="photos-sections">
  <div class="row container" id="photos">



(function pushImages() {
                //array of images, better to store in an object ?
  var images = ["07750013.jpg", "07750015.jpg", "07770021.jpg", "08210019.jpg", "08220021.jpg", "08230008.jpg", "08240009.jpg", "14990007.jpg", "15000008.jpg", "15000009.jpg", "15010024.jpg", "15020018.jpg", "15020021.jpg", "15030012.jpg", "15030025.jpg"];
  var placeHolder = document.getElementsByClassName("container");
  for (var i = 0; i < images.length; i++) {

    var markUp = ("<div class='col-md-3'><img src='img/" + images[i] + "' class='img-responsive'</img></div>");
    placeHolder[0].insertAdjacentHTML("beforeend", markUp);


You don't need to loop through each image if you just want to put one in each container. You should also generate the number of placeholder from the number of images.