frankw
frankw

Reputation: 15

Add divs with classes with image inside with JS

I am trying to write some JS so that the end result adds this to the HTML. I plan to have an array of images to index through and populate the page with images. Is there a simple way of doing this? Will I need to switch the classes to IDs for each image?

<div class="box">
    <div class="boxInner">
        <img src="http://placehold.it/480x480"/>
    </div>
</div>

I have figured out how to add a div with a class.

var newInner = document.createElement('div');
newInner.className = 'boxInner';
document.getElementById("wrap").appendChild(newInner);

I also figured out how to append an image. I am stuck trying to put all of these together.

var newImage = document.createElement("img");
newImage.setAttribute("src", "http://placehold.it/480x480");
document.getElementById("wrap").appendChild(newImage);

Upvotes: 1

Views: 456

Answers (2)

Zackary Murphy
Zackary Murphy

Reputation: 411

Assuming you have an array with the img srcs and a div with the id of 'box':

var box = document.getElementById('box');
for (var i = 0; i < imgs.length; i++) {
    var newInner = document.createElement('div');
    newInner.className = 'boxInner';
    var newImage = document.createElement('img');
    newImage.setAttribute('src', imgs[i]);
    newInner.appendChild(newImage);
    box.appendChild(newInner);
}

Upvotes: 0

Device
Device

Reputation: 567

This is one way of doing it.

var images = ["http://cdn.arstechnica.net/wp-content/uploads/2016/02/5718897981_10faa45ac3_b-640x624.jpg", "http://cdn.arstechnica.net/wp-content/uploads/2016/02/5718897981_10faa45ac3_b-640x624.jpg", "http://cdn.arstechnica.net/wp-content/uploads/2016/02/5718897981_10faa45ac3_b-640x624.jpg", "http://cdn.arstechnica.net/wp-content/uploads/2016/02/5718897981_10faa45ac3_b-640x624.jpg"];

for (var i = 0; i < images.length; i++) {
  var container = document.getElementById("container");
  var imgElement = document.createElement("img");
  imgElement.src = images[i];
  container.appendChild(imgElement);
} 
<div id="container"></div>

Upvotes: 1

Related Questions