I am quite new to this and have been looking for a way to make a 'delete' button with the assigned eventListener to remove the element it relates to(li).
I don't know JS as well yet, so it might not be the best way to do that, but that's what I have so far:
A simple HTML
<h1>The List</h1>
<ul>
<li>Delete me<button id="del">x</button></li>
<li>Delete me too<button id="del">x</button></li>
</ul>
I would like to make each 'del' button to delete its parent - 'li' where this button is nested.. and I want to write a reusable function.
I can sort of get an idea that I need to "make the click function to delete child(li) of parent(ul)". How can I connect specific 'li' with the 'button' nested in it?
I was also thinking maybe be loop through to give it an unique id or a number.. I am a bit lost here, could you please suggest me what can be done, considering I'm really new and cannot do any frameworks yet, just want to be able to do it in JS.
I made this to try, but that's too specific, eventually it needs to reusable for any of them without knowing the order:
const parent = document.getElementsByTagName('ul')[0];
const child = parent.getElementsByTagName('li')[0];
const del = document.getElementById('del');
function removeMe() {
parent.removeChild(child);
}
del.addEventListener('click', removeMe);
Thank you!
Because you want to add the same logic on multiple buttons you should use classes
instead of ids
. The ID should be unique. With Element.closest() you can find the closest parent from where the click happened until it finds a node that matches the provided selector string. Read the comments inside the code sample here
// deleteButtons is will be an array of buttons
const deleteButtons = document.querySelectorAll('.del');
deleteButtons.forEach( button => {
// add the event listener to each button
button.addEventListener('click', removeMe);
});
function removeMe() {
// this is the button
// from the button you want to move up in DOM
// and find the closes <li> to remove
this.closest('li').remove();
}
<h1>The List</h1>
<ul>
<li>Delete me<button class="del">x</button></li>
<li>Delete me too<button class="del">x</button></li>
</ul>