1

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?

gre_gor
  • 6,669
  • 9
  • 47
  • 52
covgdn
  • 55
  • 5

2 Answers2

3

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>
Youssouf Oumar
  • 29,373
  • 11
  • 46
  • 65
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>
Dai
  • 141,631
  • 28
  • 261
  • 374