Reputation: 39
i wanna ask what does this function do and what does the "element.parentNode.parentNode" mean?
function removeToDo(element){
element.parentNode.parentNode.removeChild(element.parentNode)
}
Upvotes: -1
Views: 861
Reputation: 25408
In the example below there is a div
of class grandparent
which is parent most and it has 2 children div
and section
which is a child of grandparent
.
But when you consider button
of class child
which is a child of parent
and grandchild
of grandparent
.
So if you gonna remove the parent
after chicking the button child
then you have to go to its parent then tell him to delete his child.
e.target.parentNode.parentNode.removeChild(e.target.parentNode);
So this is what this instructs, as you are on child
then you have to go to its parent of parent i.e grandparent
to remove the child parent
.
If you remove a node then all of its children will also get removed.
When you click a button you will get the event object not the node, so you have to select the node from
e.target
thene.target.parentNode
to get the parent node.
const grandparent = document.querySelector(".grandparent");
const parent = document.querySelector(".parent");
const child = document.querySelector(".child");
child.addEventListener("click", e => {
e.target.parentNode.parentNode.removeChild(e.target.parentNode);
})
body {
margin: 1rem;
}
.container {
border-radius: 1.25rem;
padding: 2rem;
}
.info {
text-align: center;
margin-bottom: 1rem;
font-weight: bold;
text-transform: uppercase;
color: white;
}
.grandparent {
background-color: darkslategray;
}
.parent {
background-color: rgb(245, 70, 17);
display: flex;
flex-direction: column;
justify-content: center;
align-items: center;
}
.child {
background-color: rgb(41, 232, 190);
}
button {
border: none;
padding: 1rem;
border-radius: 4px;
}
<div class="grandparent container">
<div class="info">Grandparent </div>
<section class="parent container">
<div class="info">Element to be removed </div>
<button class="child"> click to remove parent </button>
</section>
</div>
Upvotes: 0
Reputation: 3910
element.parentNode => parentNode 2 element.parentNode.parentNode => parentNode 1
element.parentNode.parentNode.removeChild => [parentNode 1].renoveChild //pseudo code
element.parentNode.parentNode.removeChild(element.parentNode) => [parentNode 1].renoveChild([parentNode 2]) //pseudo code
So parentNode 2 will be removed along with all it's children
Upvotes: 0