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

118
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar

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 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