0

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:

  1. I can't fetch the buttons. The node list seems to be empty in console.
  2. 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>
Heretic Monkey
  • 11,687
  • 7
  • 53
  • 122
  • Could you please create a StackBlitz with the code and attach the link? – Raz Luvaton Aug 04 '21 at 15:57
  • You call your `forEach` on a list of created buttons that existed when the page loaded, not a live list. Use event delegation. – Heretic Monkey Aug 04 '21 at 16:01
  • 1
    Does this answer your question? [Event binding on dynamically created elements?](https://stackoverflow.com/questions/203198/event-binding-on-dynamically-created-elements) – Heretic Monkey Aug 04 '21 at 16:01

1 Answers1

0

Please use this 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";
    addEventToBtns();
}

btnAdd.addEventListener("click", createBtn);

function DeleteTheBtns () {
    console.log("It works!!!")
}
function addEventToBtns() {
    const allCreatedBtns = document.querySelectorAll(".created");
    allCreatedBtns.forEach(btn => btn.addEventListener("click", DeleteTheBtns))
}

In "createBtn()" function, add "addEventToBtns()" function.

Kirill Savik
  • 1,228
  • 4
  • 7