i don’t want to use this method because if there’s multiple elements with same id they will all be removed
i need a method to only delete the parent element of the button that was clicked.
Because if you execute this code and click the button it will delete all elements with the id of "div-list" but i only want it to delete the parent element of only the button that clicked it
let button = document.getElementById('button-submit');
let div = document.getElementById('div-list');
div.appendChild(button);
button.onclick = () => {
div.remove();
}
i found a way that works but i want another one that is only javascript here’s the method that works but i hope there’s another way to do it:
<div>
<button onclick="this.parentElement.remove()"></button>
<div>
5
Answers
All DOM elements in javascript have the
.parentElement
property. This means that in thebutton.onClick
function you can simply say:button.parentElement.remove();
Thus removing only the parent.
An event listener receives an event as the first argument. That event has
currentTarget
as a property, which points to the element to which the event handler is attached (in your case thebutton
).And for that element you can use the
parentElement
:As a note: You should not use the
on...
properties to attach events, instead useaddEventListener
:With the
on...
properties, you can only attach one event handler of a particular event to an element, which can result in hard-to-debug problems in a larger code base when you accidentally overwrite an event handler that still should exist on the element.Using ID’s is not really ideal.
When you have multiple Elements you want to do the same too, it’s usually better to use something called delegated events.
This works by adding your
click
handler onto a parent element.items
and then checking the target to see if it’s the element your after.remove
, you can then find the parent.item
of this element and remove.A bonus to this approach is if you later dynamically add items, the events will work for them also. Also notice in the example below I’ve used
closest
, the advantage toparentElement
is that it will continue to work if you alter the layout later.Below is a simple example..
First, let’s test your theory
As we can see, an event is attached to the very first
input
inside the element of the givenid
and its parent will be removed. Which brings us to a very important point to make:Duplication of ids is invalid in HTML and should be avoided whenever possible
So, convert your
button-submit
anddiv-list
ids to classes and do the following:I ignored adding your buttons into your divs for now, because you have given us no contextual information about the structure that you have.