我想问一下这个函数是做什么的,“element.parentNode.parentNode”是什么意思?
function removeToDo(element){
element.parentNode.parentNode.removeChild(element.parentNode)
}
我想问一下这个函数是做什么的,“element.parentNode.parentNode”是什么意思?
function removeToDo(element){
element.parentNode.parentNode.removeChild(element.parentNode)
}
element.parentNode => parentNode 2 element.parentNode.parentNode => parentNode 1
element.parentNode.parentNode.removeChild => [parentNode 1].renoveChild //伪代码
element.parentNode.parentNode.removeChild(element.parentNode) => [parentNode 1].renoveChild([parentNode 2]) //伪代码
所以 parentNode 2 将连同它的所有子节点一起被删除
在下面的示例中,有一个div
of 类grandparent
,它是最父类,它有 2个子类div
,section
它是 的一个子类grandparent
。
但是当您考虑作为和的子button
级的类时。child
parent
grandchild
grandparent
因此,如果您要parent
在点击按钮后删除它,child
那么您必须去找它的父母,然后告诉他删除他的孩子。
e.target.parentNode.parentNode.removeChild(e.target.parentNode);
所以这就是它所指示的,当你在时,child
你必须去它的父母的父母,即grandparent
删除孩子parent
。
如果您删除一个节点,那么它的所有子节点也将被删除。
e.target
当您单击按钮时,您将获得事件对象而不是节点,因此您必须从中选择节点e.target.parentNode
才能获得父节点。
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>