Skip to content
Advertisement

How to add event listener to all elements

I am generating input fields and a font awesome icon dynamically via JavaScript. I want to attach an event that alerts a string to each created icon, currently the event works only for the first created icon, how can I attach the event to all icons? Here is my code:

createNewPricedRoundShareholder() {
      var newPlatformNameInputContainer = document.getElementById(
        "round-shareholder-container"
      );

      const newPlatformNameInput = document.createElement("input");
      newPlatformNameInput.classList.add("form-control");
      newPlatformNameInput.classList.add("input");
      newPlatformNameInput.placeholder = "Username";
      newPlatformNameInput.setAttribute("type", "text");
      newPlatformNameInput.setAttribute("name", "username");

      newPlatformNameInputContainer.appendChild(newPlatformNameInput);

      var secondContainer = document.getElementById(
        "round-investment-container"
      );

      const newInitialOptionsPool = document.createElement("input");
      newInitialOptionsPool.classList.add("form-control");
      newInitialOptionsPool.classList.add("input");
      newInitialOptionsPool.placeholder = "Investment";
      newInitialOptionsPool.name = "investment";
      newInitialOptionsPool.setAttribute("type", "text");
      newInitialOptionsPool.setAttribute("name", "investment");
      secondContainer.appendChild(newInitialOptionsPool);
      secondContainer.innerHTML += '<i class="fas fa-trash"></i>';

       document.querySelectorAll(".fa-trash").addEventListener('click', function() {
        alert('CLICKED');
      });
    }

Advertisement

Answer

You need to loop over the elements (you should have an error on your console).

Instead of

document.querySelectorAll(".fa-trash").addEventListener('click', function() {
     alert('CLICKED');
});

you should use

 document.querySelectorAll(".fa-trash").forEach( 
      function(el){
           el.addEventListener('click', function() {
               alert('CLICKED');
           })
      }
)
Advertisement