I am constructing a Hanoi Tower, but I'm coming across problems involving parenting elements. I am trying to move the disks using remove a child and append child. Every tower and disk has an ID, but when I try to target a tower ID I get a disk ID.
<body>
<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>
<script src="script.js"></script>
</body>
const container = document.querySelector(".container")
const towers = document.querySelectorAll(".tower")
const disks = document.querySelectorAll(".disk")
let chosenDisc = ""
let chosenTower = ""
towers.forEach(choice => choice.addEventListener("click", (e) => {
chosenTower = e.target.id
}))
disks.forEach(choices => choices.addEventListener("click", (e) => {
chosenDisc = e.target
chosenTower.removeChild(chosenDisc)
container.appendChild(chosenDisc)
}))
I did not put all IDs selections there, just classes to not long too much, but they are just the name plus numbers.
CodePudding user response:
chosenTower
is a string and you need to convert it as Element while chosenDisc
is a Element object because e.target
return Element object. You can use querySelector
function to convert it an Element like following
You should replace
chosenTower = e.target.id
to
chosenTower = document.querySelector('#' e.target.id);
CodePudding user response:
Easiest way out is to ask JS for parent element of Disk ID like this:
disks.forEach((choice) =>
choice.addEventListener(
"click",
(e) => {
chosenDisk = e.target.id;
chosenTower = e.target.parentElement.id;
console.log(chosenDisk, " is in ", chosenTower);
},
)
);