admin管理员组文章数量:1300174
I have this in my html page:
<nav>
<a></a>
<a></a>
</nav>
but when I run var menuitem = document.getElementsByTagName('nav').childNodes;
it returns "undefined".
Here is the entire javascript file with the relevant part at the end:
What did I do wrong?
Thanks for the help guys!
I have this in my html page:
<nav>
<a></a>
<a></a>
</nav>
but when I run var menuitem = document.getElementsByTagName('nav').childNodes;
it returns "undefined".
Here is the entire javascript file with the relevant part at the end: http://pastebin./bVj2Ug4e
What did I do wrong?
Thanks for the help guys!
Share Improve this question asked Aug 14, 2012 at 13:32 cmpliegercmplieger 7,37116 gold badges56 silver badges85 bronze badges 3-
4
getElementsByTagName
returns aNodeList
not a single element: developer.mozilla/en-US/docs/DOM/NodeList – Felix Kling Commented Aug 14, 2012 at 13:34 - 1 Additionally, and that's the whole point, your DOM is not yet loaded when you execute this code. – ldiqual Commented Aug 14, 2012 at 13:35
- 2 @SnippetSpace Yes, even if there's only one. Not doing so would be far too inconsistent. – Anthony Grist Commented Aug 14, 2012 at 13:35
2 Answers
Reset to default 8this may work for you
var menuitem = document.getElementsByTagName('nav')[0].childNodes;
as document.getElementsByTagName('nav') will return nodeList, and make sure you are running javascript after the dom ready.
You are applying .childNodes
on a NodeList.
NodeList Works Similar to Array But Not an array datatype in JavaScript.
In your Case, document.getElementsByTagName('nav')
is returning a NodeList.
So you will have to select First Element of Array and then add ".childNodes
" after it:
let menuitem = document.getElementsByTagName('nav')[0].childNodes;
You can also Use "document.getElementByTagName()
" Method Instead of "document.getElementsByTagName()
" if you don't need a Nodelist and Just a Single Node. In that case you will not need to select first element of node list. You can do this in following way:
let menuitem = document.getElementByTagName('nav').childNodes;
本文标签: javascriptSearching for childNodes returns undefinedStack Overflow
版权声明:本文标题:javascript - Searching for childNodes returns undefined - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1741619454a2388722.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论