Solution 1 :

Use this code:

function addImages(){
    for(var i=0; i<3; i++){
       var imgDiv = document.createElement("div");
       imgDiv.id = "div"+i;
       var image = document.createElement("img");
       image.setAttribute("src", "https://picsum.photos/100/150");
       imgDiv.appendChild(image); 
       document.getElementsByTagName('body')[0].appendChild(imgDiv);
       }
   }

getElementById looks for the id attribute of elements. body is the tag name, so we should use getElementsByTagName instead. This returns an HTMLCollection and we get the first object by [0].

Solution 2 :

I’ve done something similar ReactJS that i believe will translate well with this.
So I created a list with the image locations and then mapped through them as such.

const addImages = () => {
    let imageList = ["image1", "image2", "image3"]

    return imageList.map(image => <div><img src={image}/></div>)
}

Problem :

I’m trying to make a function that will create a div, append an image in the div, and then append the div onto the body, 3 times using a for loop. I’m new to JS and this is stumping me, can anyone let me know what I’m doing wrong here?

function addImages(){
    for(var i=0; i<3; i++){
       var imgDiv = document.createElement("div");
       imgDiv.id = "div"+i;
       var image = document.createElement("img");
       image.setAttribute("src", "https://picsum.photos/100/150");
       imgDiv.appendChild(image); 
       document.getElementById('body').appendChild(imgDiv);
       }
   }

Comments

Comment posted by imvain2

Does your body tag have an id of body? you can always use:

Comment posted by Bulent

document.querySelector(‘body’).appendChild(imgDiv);

Comment posted by hdnshk

@imvain2 thanks for pointing that out, I changed it to

Comment posted by jsfiddle.net/2no76rut

I tried the code with document.body and it does work. So are you actually calling

Comment posted by hdnshk

@imvain2 I had another issue in my file preventing it from running! I just tried yours, and it works perfectly! Thank you a ton.

Comment posted by hdnshk

Thanks for the reply! I just tried it, and there is still no output.

By