Child element innerHTML retrieved in firstChild is undefined

Asked 1 years ago, Updated 1 years ago, 103 views

After pressing the button, obtain the first child element of the element and the contents of the element (e.g.a)I would like to see in a dialog, but it says undefined.How do I fix this?

<!DOCTYPE html>
<html lang="ja">
<head>
  <metacharset="utf-8">
  <title> Ayeo Shop </title>

  <link href="css/bootstrap.min.css"rel="stylesheet">
  <link type="text/css"rel="stylesheet" href="css/bootstrap-timepicker.min.css">
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.4/jquery.min.js"></script>
  <script src="js/bootstrap.min.js"></script>
  <body>
    <divid="childcatch">
      <span>a</span>
      <span>b</span>
      <span>c</span>
      <span>d</span>
      <span>e>/span>
    </div>
    <script type="text/javascript">
      function findElement(){
        variable= document.getElementById("childcatch");
        varchild = element.firstChild;
        alert(child.innerHTML);
      }
    </script>
    <button onclick="findElement()">Get First Child</button>
  </body>
  </html>

javascript html5 dom

2022-09-29 22:19

2 Answers

In conclusion, firstElementChild instead of firstChild will solve the problem.

firstChild returns a node, not limited to Element, with a new line and a blank space between <divid="childcatch"> and <span>a</span>, where text node is created.And the text node does not have the innerHTML property, so undefined returned.


2022-09-29 22:19

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.