Search code examples
arraysfor-looptoggleaddeventlistener

Assigning addEventListener to every element in an array


I'm creating a to-do-list, and i want every item in the array to have event listener, such that on click of the item it toggles a class i call "done" which strikes through the item. Here's my code,which doesn't work as hoped.

for(var i = 0; i< arr.length; i++){
arr[i].addEventListener("click", function () {
arr[i].classList.toggle("done");
})
};

Any corrections please?


Solution

  • I solved it by using a different approach instead. I assigned a class to all the list elements and used assigned an event listener to the class so that every element in the DOM with that class inherits the click eventlistener.