Search code examples
javascriptevent-listenerappendchild

Event listener not being appended for all elements


I've appended multiple anchor tag elements to my document, but only the first anchor tag triggers the function that I have at the bottom of my Javascript document.

HTML:

<!DOCTYPE html>
<html lang="en">
  <head>
    <title>To-Do App</title>
  </head>
  <body>
    <div id="toDos"></div>
    <script src="js/todo-app.js"></script>
  </body>
</html>

Javascript:

let toDo = [{title: "groceries"},{title: "laundry"},{title: "cook dinner"},];
const filters = {searchText: ''}
const renderToDos = function (toDo, filters) {
  const filteredToDos = toDo.filter(function (todo) {
    return todo.title.toLowerCase().includes(filters.searchText.toLowerCase());
  });
  filteredToDos.forEach(function (todo) {
    const toDoElement = document.createElement('p');
    toDoElement.setAttribute('class', 'paragraph');
    const toDoDelete = document.createElement('a');
    toDoDelete.setAttribute('href', '#');
    toDoDelete.textContent = "Delete Item";
    toDoElement.textContent = todo.title;
    document.querySelector('#toDos').appendChild(toDoElement);
    document.querySelector('#toDos').appendChild(toDoDelete);
  });
}
renderToDos(toDo, filters);
// The function I'm trying to trigger with the remaining anchor tags
document.querySelector('a').addEventListener('click', function () {console.log("item deleted");});

Solution

  • To clarify a mistake in my comment, it is not necessary to use Array.from() to convert the result since querySelectorAll returns a NodeList and not an HTML Collection.

    NodeLists have a built-in forEach method so it would not need to be converted in this exmaple. However, if you wanted access to most other array methods, particularly looping methods like map and filter, you would have to do it.

    I believe this syntax should work for your code:

    document.querySelectorAll('a').forEach(el => {
      el.addEventListener('click', () => console.log('item deleted'))
    })