Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

114
Visualizações
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 Respostas
Responde à pergunta

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 Relatório

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda