user16327774
user16327774

Reputation:

how can i create div using loop. i found this code in a book but it isnt working

This code is not creating a single div in the webpage which i linked the js below. how can i makes changes in the js or html for the code to be executed as expected

var div,
  container = document.getElementById("container");
for (var i = 0; i < 5; i++) {
  div = document.createElement("div");
  div.onclick = function () {
    alert("This is box #" + i);
  };
  container.appendChild(div);
}

Upvotes: 0

Views: 144

Answers (1)

DecPK
DecPK

Reputation: 25401

1) To show a div you have to include some text inside divtag

2) You should use let instead of var to get the correct number when user click on div

var div,
  container = document.getElementById("container");
for (let i = 0; i < 5; i++) { // change -> let instead of var
  div = document.createElement("div");
  div.textContent = `div${i}` // change -> add some text
  div.onclick = function() {
    alert("This is box #" + i);
  };
  container.appendChild(div);

}
<div id="container"></div>

Upvotes: 1

Related Questions