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

115
Visualizações
Get the id of the first div element inside a container div

I've cut down my page to just the relevant content. See code here:

let text = document.getElementById("apanelofcontent").firstChild.id;
console.log(text);
<div class="apanelofcontent" id="apanelofcontent">
  <div class="panel1" id="panel1" name="panel1">
    <p>Content goes here</p>
  </div>
  <div class="panel1link" id="panel1link">
    <p><a href="#ex1" rel="modal:open">Open modal</a></p>
  </div>
</div>

All I want to do is get the id value from the first div to appear within the div with the apanelofcontent as id.

So in the above example I want the console to display the text panel1 as that’s the id of the first div to appear within the div with apanelofcontent as id.

If I run the above, all I get in the alert window is undefined. What am I doing wrong?

about 4 years ago · Santiago Trujillo
2 Respostas
Responde à pergunta

0

firstChild could be just a text node, that space before the div, which doesn't have an id. You could use firstElementChild, which gets you the first element node, like so:

<html>
  <div class="apanelofcontent" id="apanelofcontent">
    <div class="panel1" id="panel1" name="panel1">
      <p>Content goes here</p>
    </div>
    <div class="panel1link" id="panel1link">
        <p><a href="#ex1" rel="modal:open">Open modal</a></p>
    </div>
      <script>
        let text = document.getElementById("apanelofcontent").firstElementChild.id;
        window.alert(text);
      </script>
  </div>
</html>

about 4 years ago · Santiago Trujillo Relatório

0

This prints panel1 to console:

let firstDivChildId = document.querySelector('div#apanelofcontent > div:first-of-type').id;
//window.alert(firstDivChildId );
console.log(firstDivChildId  )
<div class="apanelofcontent" id="apanelofcontent">
  <div class="panel1" id="panel1" name="panel1">
    <p>Content goes here</p>
  </div>
  <div class="panel1link" id="panel1link">
    <p><a href="#ex1" rel="modal:open">Open modal</a></p>
  </div>
</div>

about 4 years ago · Santiago Trujillo 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