I have an ul with class "items". Each li has item-card class. I have a variable named itemCards in my JS file containing a NodeList with li.item-card elements.
I can add dynamically a new li with item-card class due to an event listener. The problem is that after the new li has been added to the ul, my variable is unmodified and doesn't contain new li. At least this is what I believe, because I have a 'click' event listener on each li.item-card, but when I click on this new element, nothing happens, so it looks like the event listener isn't active on this new added element. How can I "update" the variable or activate the event listener on the new added element?
Here:
Click on any task: log a message
Press enter: add a new task
Expected result: I want to log the same message if I click on the new li, but nothing happens
const itemCards = document.querySelectorAll(".item-card");
itemCards.forEach( itemCard => { itemCard.addEventListener('click', (e) => {
console.log("Task Clicked");
})});
document.addEventListener('keyup', (e) => {
if(e.keyCode == 13) {
// TODO: add new div task
const newLi = document.createElement("li");
newLi.classList.add("item-card");
const label = document.createElement("label");
label.classList.add("task-label");
label.textContent = "New Task";
newLi.appendChild(label);
console.log(newLi);
e.target.value = "";
document.querySelector("ul.items").appendChild(newLi);
}
})
<ul class="items">
<li class="item-card">
<i class="fa-regular fa-circle circle"></i>
<label class="task-label">Task 1</label>
<i class="fa-solid fa-xmark xmark"></i>
</li>
<li class="item-card">
<i class="fa-regular fa-circle-check circle check-circle"></i>
<label class="task-label">Task 2</label>
<i class="fa-solid fa-xmark xmark"></i>
</li>
</ul>