I'm trying to code a function that will loop through the child nodes of my “main” div element, and outputting element tag names out onto an hmtl page and every time I try to compile my code i end up getting undefined. Can anyone shed some light as to why?
Could it be because Console.log returns undefined? But if it does shouldn't I still be receiving some sort of output from my for loop?
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();
Your are probably call the javascript before DOM is ready. Put the call to the function just before ending body tag.
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]);
}
}
Call the looper just before body tag to ensure the availability of DOM elements.
<script type="text/javascript" >
looper();
</script>
</body>
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.