I just started studying JS and I'm currently simulating something that will apply to my project Basically, I'm trying to generate new Divs with Button on it in order to do something. And I applied the for loop on the button from the guide here Turns out it works! but there's a bug where some buttons wont work whenever I generate more divs+button and I don't know why?
const btnCreate = document.querySelector(".myButton");
const changeBtn = document.getElementsByClassName("changeBtnStyle");
const newNewDiv = document.getElementsByClassName("newCDiv");
const createFunc = function() {
const parentDiv = document.querySelector(".parentDiv");
const newDiv = document.createElement("div");
const newChangeBtn = document.createElement("button");
parentDiv.appendChild(newDiv);
newDiv.appendChild(newChangeBtn);
newDiv.classList.add("newCDiv");
newChangeBtn.classList.add("changeBtnStyle")
newChangeBtn.innerHTML = "change"
for (let i = 0; i < changeBtn.length; i++) {
changeBtn[i].addEventListener("click", function() {
newNewDiv[i].classList.toggle("changeColor");
}, false);
}
};
btnCreate.addEventListener("click", createFunc);
.parentDiv {
margin: auto;
width: 300px;
height: 300px;
background-color: gray;
position: relative;
}
.newCDiv {
background: green;
width: 50px;
height: 50px;
position: relative;
}
.changeBtnStyle {
position: absolute;
}
.changeColor {
background: red;
}
.myButton {
margin: auto;
}
<button class="myButton">
Create Div w/ Button
</button>
<div class="parentDiv">
</div>
Here's the JSFiddle one