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]
.
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>)
}
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);
}
}
I tried the code with document.body and it does work. So are you actually calling
@imvain2 I had another issue in my file preventing it from running! I just tried yours, and it works perfectly! Thank you a ton.
Thanks for the reply! I just tried it, and there is still no output.