0

I have been reading similar questions, but the most common problem is selecting a string, which is not my case.

const container = document.querySelector(".container")
const towerOne = document.querySelector("#towerOne")
const discs = document.querySelectorAll(".disc")

let chosen

discs.forEach(choices => choice.addEventListener("click", (e) => {
    chosen = e.target.id
    towerOne.removeChild(chosen)
    container.appendChild(chosen)
}))

I've tried declaring let chosen as " " before but changing it modified anything.

  • Use [event delegation](//developer.mozilla.org/docs/Learn/JavaScript/Building_blocks/Events#Event_delegation) instead of assigning multiple event listeners — it’s more maintainable, and applies to dynamically added elements. E.g., use an [event argument](//developer.mozilla.org/docs/Web/API/EventTarget/addEventListener#The_event_listener_callback)’s [`target`](//developer.mozilla.org/docs/Web/API/Event/target). See [the tag info](/tags/event-delegation/info) and [What is DOM Event delegation?](/q/1687296/4642212). – Sebastian Simon Sep 25 '21 at 16:53

1 Answers1

0

chosen is the id attribute of an element. You'll want to get the target of the event instead:

const container = document.querySelector(".container")
const towerOne = document.querySelector("#towerOne")
const discs = document.querySelectorAll(".disc")

let chosen

discs.forEach(choices => choice.addEventListener("click", (e) => {
    chosen = e.target
    towerOne.removeChild(chosen)
    container.appendChild(chosen)
}))
Spectric
  • 30,714
  • 6
  • 20
  • 43