This has been asked before but I truly couldn't apply any of the answers to my simple case. I have no idea what I am doing wrong. Upon click on the button I dynamically create several buttons. Then, I want to fetch all the buttons and add to each of them eventListener. The problem is:
- I can't fetch the buttons. The node list seems to be empty in console.
- I have tried to push each dynamically created button to an Array and then use forEach method to add eventlistener and this also does not work. It should work with a normal querySelectorAll in such a simple case.
This is my entire code:
const main = document.querySelector(".main");
const btnAdd = document.querySelector(".add");
const theArray = [];
const createBtn = (e) => {
e.preventDefault();
const ButtonCreated = document.createElement("button");
main.appendChild(ButtonCreated).classList.add("created");
ButtonCreated.textContent = "Created button"
}
btnAdd.addEventListener("click", createBtn);
function DeleteTheBtns() {
console.log("It works!!!")
}
const allCreatedBtns = document.querySelectorAll(".created");
allCreatedBtns.forEach(btn => btn.addEventListener("click", DeleteTheBtns))
.add {
align-self: flex-end;
height: 80px;
width: 100px;
background-color: crimson;
margin-right: 100px;
margin-top: 50px;
}
.created {
align-self: flex-start;
height: 80px;
width: 100px;
margin-left: 20px;
}
<div class="main">
<button class="add">Add</button>
</div>