Given this markup:
<ul id="navtabs">
<li><a onClick="someFunction();" href="#">Link</a></li>
<li><a onClick="someFunction();" href="#">Link</a></li>
</ul>
and this function:
function someFunction(){
navList=document.getElementById('navtabs').childNodes;
for(i=0;i<navList.length;i++){
navList[i].childNodes[0].className='fgf';
}
}
my expectaction is that the class of each anchor is changed, however, when the function runs I get:
Error: navList[i].childNodes[0] is undefined
When I use:
navList[i].className='fgf';
in lieu of the above code, the class name of the list item is changed as expected.
How can i access the childNode of the childNode through the loop as seen in the above function?
Thank you.
childNodesis likely giving you text nodes as well as dom elements, which is why you’re getting that error. In your loop,navList[i]is at times a text node with no children of its own, which is of course whynavList[i].childNodes[0]isundefinedInstead of using
childNodesyou could doto just get the child elements. But I would recommend being even more specific with
getElementsByTagName