Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

119
Views
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 answers
Answer question

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 Report

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!