Hello guys after some effort I managed to create a loop for my images withing my array, I would like to know if this is a good way to do it or if I should fix or change something especially in the
You don’t need to have img as an argument in createImageNode().
Also, why not just use a for loop in stead of foreach. It makes it easier to change the number of images you want.
var images = 3;
var arrayImagesElement = document.getElementById("arrayImages");
function createImageNode() {
var img = document.createElement('img');
img.src = "https://insider.directv.com/wp-content/uploads/2012/07/nemo_big.jpg";
img.width = "300";
img.style.margin = "15px";
return img;
}
for(var i = 0; i < images; i++){
arrayImagesElement.appendChild(createImageNode());
};
Thanks alot for your help super handy!! I was also trying To make the same exercise but with different images but its just not working can I have your help for this one too please.
HTML
<div id="imageContainer"></div>
JS
var images = ['1.png','2.png','3.png','4.png'];
var container = document.getElementById('imageContainer');
function createImageNode() {
var imgs = document.createElement('img');
imgs.src = images;
imgs.width = "300";
imgs.style.margin = "15px";
return img;
}
for(var i = 0; i < images; i++){
container.appendChild(createImageNode());
};
Thats one way to do it. I would prefer to use your original code but add an argument for the individual image links. This way you avoid using container inside of your function. Its generally better to only pass variables as arguments into your functions. This avoids more work if you ever change the variable or variable name.
In this case, using foreach is good because each element in the array is necessary when calling the function.
Using your original code but changing the function:
var images = ['1.png','2.png','3.png','4.png'];
var arrayImagesElement = document.getElementById("arrayImages");
function createImageNode(imgSrc) {
var img = document.createElement('img');
img.src = imgSrc;
img.width = "300";
img.style.margin = "15px";
return img;
}
images.forEach(img => {
arrayImagesElement.appendChild(createImageNode(img));
});