0

我正在尝试编写一个函数,该函数将遍历我的“主” div 元素的子节点,并将元素标签名称输出到 hmtl 页面上,每次我尝试编译我的代码时,我都会得到未定义的结果。任何人都可以解释为什么?

可能是因为 Console.log 返回未定义?但如果它不应该我仍然从我的 for 循环中接收某种输出?

function looper() {         //function that will loop through the child nodes of main

    var nodes = document.getElementById('main').childNodes;

    for(i=0; i<nodes.length; i++) {
        console.log(nodes[i]);
    }
}

HTML

 <div id ="main">

 <h1> Jimms web site </h1>

 <nav>
   <a href="index.html">Home page</a> |
   <a href="about.html">About me</a> |
   <a href="contact.html">Contact me</a> 
 </nav> 

     <p> This is a list: </p>
     <div> 
     <ol id = "list">
      <li><a href="mega">hi</a> - </li>
      <li><a href="mario">mario</a> - </li>
      <li><a href="luigi">luigi</a> - </li>
      <li><a href="mash">mash</a> - </li>
      <li><a href="mash">mash</a> - </li></ol>
      </div>
      <p> Thats it </p>



 </div>

  looper();
4

1 回答 1

0

您可能在 DOM 准备好之前调用了 javascript。在结束 body 标记之前调用函数。

现场演示

function looper() {         //function that will loop through the child nodes of main

    var nodes = document.getElementById('main').childNodes;

    for(i=0; i<nodes.length; i++) {
        document.write(nodes[i]);
    }
}

在 body 标记之前调用 looper 以确保 DOM 元素的可用性。

    <script type="text/javascript" >
        looper();
    </script> 

</body>   
于 2013-07-17T06:52:05.797 回答