cmplieger
cmplieger

Reputation: 7371

Searching for childNodes returns undefined

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.com/bVj2Ug4e

What did I do wrong?

Thanks for the help guys!

Upvotes: 1

Views: 9955

Answers (2)

Shaharyar Ansari
Shaharyar Ansari

Reputation: 1

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;

Upvotes: 0

Shreedhar
Shreedhar

Reputation: 5640

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.

Upvotes: 8

Related Questions