addEventListener() and createElement()

Nagisa Ando :

I would like to ask how I can execute addEventListner() to the element that I created with createElement().

I have a add button in my project and when I click it, it will create an another add button, and keep making add button with the button.

but my first button works and keep creating new buttons, but the other buttons do not do anything.

Here is my code.

const addBtn = document.querySelector('.button');
const total = document.getElementById('amount-total');



addBtn.addEventListener('click', addButton);


let counter = 0;
function addButton(){
    counter++;

    let newDiv = document.createElement('div');
    newDiv.id = 'new-container' + counter;
    total.parentNode.insertBefore(newDiv, total)


    let createBtn = document.createElement('button');
    createBtn.innerHTML = '+';
    createBtn.className = 'button';

    newDiv.appendChild(createBtn);
}

but it didn't work so I tried querySelectorAll instead.

const addBtns = document.querySelectorAll('.button');
addBtns.forEach(btn => btn.addEventListener('click', addButton))

but still the original one works but other one don't. I am new to javascript, and really appreciate if you could help me out.

Thank you.

Ken Geelhoed :

If I understand correctly, you should add the addEventListener('click', addButton) in the function addbutton(). In this way you also create a new button every time you clicked an added button. Your code:

const addBtn = document.querySelector('.button');
const total = document.getElementById('amount-total');



addBtn.addEventListener('click', addButton);


let counter = 0;

function addButton() {
  counter++;

  let newDiv = document.createElement('div');
  newDiv.id = 'new-container' + counter;
  total.parentNode.insertBefore(newDiv, total)


  let createBtn = document.createElement('button');
  createBtn.innerHTML = '+';
  createBtn.addEventListener('click', addButton); //added this line here!
  createBtn.className = 'button';

  newDiv.appendChild(createBtn);
}

Hope this helps your understanding.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=34432&siteId=1