Sudhanshu Saini
Sudhanshu Saini

Reputation: 63

adding div dynamically using only javascript

Here is the part of my code.

I want to create a div element dynamically using JavaScript only; I am doing it for the first time using code from different websites and questions from here only.

But this loop seems to be doing nothing.

All the classes do exist in the CSS. Please, find the error and any other suggestions are most welcome.

var i;

for (i = 0; i < 20; i++) {
  var main = document.getElementById('show');

  var div1 = document.createElement('div');
  div1.id = 's' + i;
  div1.className = 'perschoolcontainer';
  var link2 = document.createElement('a');
  link2.setAttribute('href', 'abcd.jpg');

  var image3 = document.createElement('img');
  image3.id = 'dp';
  image3.src = 'davsv.jpg';
  image3.class = 'dp';

  var p4 = document.createElement('p');
  p4.id = 'sname';
  p4.class = 'sname';

  var p5 = document.createElement('p');
  p5.id = 'location';
  p5.class = 'location';

  var t1 = document.createTextNode('abc');
  var t2 = document.createTextNode('def');

  p5.appendChild(t2);
  p4.appendChild(t1);
  link2.appendChild(image3);
  link2.appendChild(p4);
  link2.appendChild(p5);
  div1.appendChild(link2);

  main.innerHTML.appendChild(div1);
}
<div id="s1" class="perschoolcontainer">
  <a href="davsv.jpg">
    <img id="dp" class="dp" src="davsv.jpg" alt="DAV">
    <div id="details" class="details">
      <p id="sname" class="sname">DAV</p>
      <p id="location" class="location">Sv</p>
    </div>
  </a>
</div>

Upvotes: 0

Views: 58

Answers (1)

trincot
trincot

Reputation: 350272

innerHTML does not have a appendChild method. Change:

main.innerHTML.appendChild(div1);

to:

main.appendChild(div1);

Upvotes: 3

Related Questions