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 a NodeList 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
Add a ment  | 

2 Answers 2

Reset to default 8

this 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