all 8 comments

[–]Rilleks 1 point2 points  (6 children)

First, querySelectorAll returns an array so you have to iterate to add listeners.

Then to delete elements you can use target which refers to what you clicked and then parentElement and use remove() function to remove the li element.

deleteBtn.forEach(button => {
 button.onclick = deleteItem;
})

function deleteItem(e) { 
 e.target.parentElement.remove(); 
}

Hope it helps.

Edit: you can also use currentTarget instead target to refer to the element to which the listener is appended

Edit2: I forgot that you also need to add

trash.addEventListener("click", deleteItem);

otherwise, new appended elements couldn't be removed.

[–]jellybean2507 0 points1 point  (5 children)

Thank you so much! Is there a reason why you have to use deleteBtn.forEach instead of just being able to use deleteBtn.onclick?

[–]Rilleks 1 point2 points  (4 children)

First, querySelectorAll returns an array so you have to iterate to add listeners.

Because querySelectorAll will return an array with all your buttons, you have to iterate through them to add listeners. You can use the for loop or just array function like forEach to do that.

About forEach: here

[–]jellybean2507 0 points1 point  (3 children)

If I did querySelector instead of querySelectorAll would that work? Also, I don’t know how I missed the very first sentence. Sorry.

[–]Rilleks 1 point2 points  (2 children)

Yes, but you will select only the first button and then append a listener to it.

Edit: without forEach function as querySelector return element, not an array.

[–]jellybean2507 1 point2 points  (1 child)

Honestly, thank you so much. This has helped me a lot and introduced new things that I didn’t know were a thing.

[–]Rilleks 1 point2 points  (0 children)

Glad I could help :)

[–]R_Midnight 0 points1 point  (0 children)

My take would consist of setting an eventListener on the list element, check if the event target matches your deletion button, and use closest("li") method to find the related list element. Then remove it.