I've trying to remove the disk as a child from a tower as a parent, but this message appears "removeChild is not a function".
let chosenDisc
let chosenTower
disks.forEach((choice) =>
choices.addEventListener("click", (e) => {
chosenDisc = e.target.id
chosenTower = e.target.parentElement.id
console.log(chosenDisc, " is in ", chosenTower)
chosenTower.removeChild(chosenDisc)
container.appendChild(chosenDisc)
})
)
<article class="container"></article>
<section class="towers">
<div class="tower" id="towerOne">
<div class="disk" id="diskOne"></div>
<div class="disk" id="diskTwo"></div>
<div class="disk" id="diskThree"></div>
<div class="disk" id="diskFour"></div>
</div>
<div class="tower" id="torreTwo"></div>
<div class="tower" id="torreThree"></div>
</section>
CodePudding user response:
I guess you are attaching an event listener only to elements that have id such as "disk*".
You are picking the id of those elements, and the id of their parent. The ID has no removeChild method, but that method is on the element theirself. In order to make your code work, you should change it as follow:
let chosenDisc
let chosenTower
disks.forEach((choice) => choices.addEventListener("click", (e) => {
chosenDisc = e.target
chosenTower = e.target.parentElement
console.log(chosenDisc.id, " is in ", chosenTower.id)
chosenTower.removeChild(chosenDisc)
container.appendChild(chosenDisc)
}))
CodePudding user response:
In the forEach loop, you are assigning the id of the parent element to chosenTower. chosenTower is not a node, it's just a string.
chosenTower = e.target.parentElement
would fix this.
CodePudding user response:
removeChild
and appendChild
are expecting a node object. you need to pass the target instead of the target.id for chosenDisc
.
let chosenDisc;
let chosenTower;
disks.forEach((choice) =>
choices.addEventListener("click", (e) => {
chosenDisc = e.target;
chosenTower = e.target.parentElement;
console.log(chosenDisc, " is in ", chosenTower)
chosenTower.removeChild(chosenDisc)
container.appendChild(chosenDisc)
})
)
<article class="container"></article>
<section class="towers">
<div class="tower" id="towerOne">
<div class="disk" id="diskOne"></div>
<div class="disk" id="diskTwo"></div>
<div class="disk" id="diskThree"></div>
<div class="disk" id="diskFour"></div>
</div>
<div class="tower" id="torreTwo"></div>
<div class="tower" id="torreThree"></div>
</section>