Reputation: 71
I want to write a function that when I click, create a DIV element inside a created DIV element. Below is my code.
The result I want to see is that one black div block contains a blue div block and display five times. But the result is five blue div blocks all in one black div block. Can someone tell me why?
function createDiv() {
for (let i = 0; i < 5; i++) {
let newDiv = document.createElement("div");
let myDiv = document.querySelector(".test");
myDiv.appendChild(newDiv);
newDiv.className = "new";
let newDiv1 = document.createElement("div");
let myDiv1 = document.querySelector(".new");
myDiv1.appendChild(newDiv1);
newDiv1.className = "inside";
}
}
.test {
width: 800px;
height: 300px;
background-color: aquamarine;
}
.new {
width: 100px;
height: 100px;
background-color: black;
display: inline-block;
}
.inside {
width: 50px;
height: 50px;
margin: 0px auto;
background-color: blue;
display: inline-block;
}
<div class="container">
<button class="btn" id="btn" onclick="createDiv()">click</button>
<div class="test" id="test">
</div>
</div>
Upvotes: 1
Views: 414
Reputation: 337560
The issue is because in each iteration of the loop you select all the .new
elements in the DOM - even those which were created in previous loop iterations.
To fix this you should use the newDiv
reference which was created within the current iteration:
let myDiv = document.querySelector(".test");
function createDiv() {
for (let i = 0; i < 5; i++) {
let newDiv = document.createElement("div");
myDiv.appendChild(newDiv);
newDiv.className = "new";
let newDiv1 = document.createElement("div");
newDiv.appendChild(newDiv1);
newDiv1.className = "inside";
}
}
.test {
width: 800px;
height: 300px;
background-color: aquamarine;
}
.new {
width: 100px;
height: 100px;
background-color: black;
display: inline-block;
}
.inside {
width: 50px;
height: 50px;
margin: 0px auto;
background-color: blue;
display: inline-block;
}
<div class="container">
<button class="btn" id="btn" onclick="createDiv()">click</button>
<div class="test" id="test">
</div>
</div>
Upvotes: 1