Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

110
Vistas
How can I target an id inside an specific class?

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.

about 4 years ago · Juan Pablo Isaza
2 Respuestas
Responde la pregunta

0

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);
     },
   )
);
about 4 years ago · Juan Pablo Isaza Denunciar

0

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);
about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda