0

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');
      });
    }
user14543107
  • 97
  • 1
  • 13
  • Does this answer your question? [Want to add "addEventListener" on multiple elements with same class](https://stackoverflow.com/questions/51573435/want-to-add-addeventlistener-on-multiple-elements-with-same-class) – Praneet Dixit Nov 30 '20 at 11:34

2 Answers2

2

You can try this method

let elementsArray = document.querySelectorAll("whatever");

elementsArray.forEach(function(elem) {
    elem.addEventListener("input", function() {
        //this function does stuff
    });
});
Mohit Chandel
  • 1,838
  • 10
  • 31
2

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');
           })
      }
)
Alberto Sinigaglia
  • 12,097
  • 2
  • 20
  • 48