matt2k12
matt2k12

Reputation: 23

how to append multiple img-child elements to a DOM element with JS?

I want to add multiple, same img-elements to a div element. Why can't I just use appendChild a couple times?

For instance:

divelement.appendChild(imgelement);
divelement.appendChild(imgelement);
divelement.appendChild(imgelement);

will result in

<div>
  <img></img>
</div>

But how can I achieve the following?

<div>
  <img></img>
  <img></img>
  <img></img>
</div>

Upvotes: 0

Views: 189

Answers (3)

S B RAKESH RATH
S B RAKESH RATH

Reputation: 481

I think You are appending same child 3 times .

an working solution is here -

const myParent = document.getElementById("someDiv");
const myImg1 = document.createElement("img");

myImg1.src = "https://picsum.photos/200/300";
myParent.append(myImg1);
const myImg2 = document.createElement("img");

myImg2.src = "https://picsum.photos/200/300";
myParent.append(myImg2);

const myImg3 = document.createElement("img");

myImg3.src = "https://picsum.photos/200/300";
myParent.append(myImg3);
*{
  margin:0;
  padding:0;
  box-sizing:border-box;
}
#someDiv{
  width:500px;
  height:200px;
  background-color:green;
  margin:auto;
    display:flex;
}
img{
  margin-right:10px;
}
<div id = "someDiv">
  
</div>

Upvotes: 0

Mr. Polywhirl
Mr. Polywhirl

Reputation: 48600

The imgelement needs to be a new instance. If you add the same child, it will do nothing.

const divElement = document.querySelector('#target');
const imgElement = document.createElement('img');

divElement.append(imgElement); // Original reference
divElement.append(imgElement); // ^ Same reference
divElement.append(imgElement); // ^ Same reference
img { width: 100px; height: 100px; background: red; }
<div id="target"></div>

You need to create a new image instance for each append action:

const divElement = document.querySelector('#target');
const createImgElement = () => document.createElement('img');

divElement.append(createImgElement());
divElement.append(createImgElement());
divElement.append(createImgElement());
img { width: 100px; height: 100px; background: red; }
<div id="target"></div>

Upvotes: 1

krisam
krisam

Reputation: 60

This way should work.

var div = document.getElementById('myId');
for(var i = 0; i < 3; i++){
      var img = document.createElement('img');
      div.appendChild(img);
}

Upvotes: 0

Related Questions