0

I am using a for loop to dynamically add div elements to a parent node in JavaScript, but I am unable to do because it adds only one element.

My code is this:

var row = document.getElementById("rowel");

var col = document.createElement('div');
col.className = "col-sm-3 col-md-3 col-lg-3 mr-auto";



var card = document.createElement('img');
card.src = "./assets/building.jpg";
card.style["max-width"] = "350px";
card.alt = "cant displayed";

col.appendChild(card);

for (let index = 0; index < 5; index++) {

    row.appendChild(col);

}

Can some please help me to solve this?

Jacob
  • 77,566
  • 24
  • 149
  • 228
ZaihamM Code
  • 87
  • 4
  • 12

2 Answers2

2

You are adding the same element in each iteration. Create a new object in every iteration and it should work

var row = document.getElementById("rowel");

for (let index = 0; index < 5; index++) {
    var col = document.createElement('div');
    col.className = "col-sm-3 col-md-3 col-lg-3 mr-auto";

    var card = document.createElement('img');
    card.src = "./assets/building.jpg";
    card.style["max-width"] = "350px";
    card.alt = "cant displayed";

    col.appendChild(card);

    row.appendChild(col);

}
flappix
  • 2,038
  • 17
  • 28
  • yes i want to add the same element, because in some situation i need the same image to display .if i will not create a new object then it wont add ?? – ZaihamM Code Mar 25 '20 at 19:49
0

When you are doing the following:

for (let index = 0; index < 5; index++) {
     row.appendChild(col);
}

you are adding 5 exact same col object.

It's like saying,

"Hey, kid A is my Child." 5 times.

In your case, it already knows that COL is a child of ROW. Its pointless to tell it million different times .

What you want is:

*"Hey, kid A is my Child."

*"Hey, kid B who looks exactly like A is my Child."

...

*"Hey, kid E who looks exactly like A is my Child."

Hence, this is what your code should look like:

for (let index = 0; index < 5; index++) {
   var col = document.createElement('div');
   col.className = "col-sm-3 col-md-3 col-lg-3 mr-auto";

   var card = document.createElement('img');
   card.src = "./assets/building.jpg";
   card.style["max-width"] = "350px";
   card.alt = "cant displayed";

   col.appendChild(card);
   row.appendChild(col);

}

Hope it helps!

A. Park
  • 94
  • 1
  • 10