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:
JavaScript
x
33
33
1
createNewPricedRoundShareholder() {
2
var newPlatformNameInputContainer = document.getElementById(
3
"round-shareholder-container"
4
);
5
6
const newPlatformNameInput = document.createElement("input");
7
newPlatformNameInput.classList.add("form-control");
8
newPlatformNameInput.classList.add("input");
9
newPlatformNameInput.placeholder = "Username";
10
newPlatformNameInput.setAttribute("type", "text");
11
newPlatformNameInput.setAttribute("name", "username");
12
13
newPlatformNameInputContainer.appendChild(newPlatformNameInput);
14
15
var secondContainer = document.getElementById(
16
"round-investment-container"
17
);
18
19
const newInitialOptionsPool = document.createElement("input");
20
newInitialOptionsPool.classList.add("form-control");
21
newInitialOptionsPool.classList.add("input");
22
newInitialOptionsPool.placeholder = "Investment";
23
newInitialOptionsPool.name = "investment";
24
newInitialOptionsPool.setAttribute("type", "text");
25
newInitialOptionsPool.setAttribute("name", "investment");
26
secondContainer.appendChild(newInitialOptionsPool);
27
secondContainer.innerHTML += '<i class="fas fa-trash"></i>';
28
29
document.querySelectorAll(".fa-trash").addEventListener('click', function() {
30
alert('CLICKED');
31
});
32
}
33
Advertisement
Answer
You need to loop over the elements (you should have an error on your console).
Instead of
JavaScript
1
4
1
document.querySelectorAll(".fa-trash").addEventListener('click', function() {
2
alert('CLICKED');
3
});
4
you should use
JavaScript
1
8
1
document.querySelectorAll(".fa-trash").forEach(
2
function(el){
3
el.addEventListener('click', function() {
4
alert('CLICKED');
5
})
6
}
7
)
8