Javascript typeof Nodelist

Tagged code, javascript

Beware of Javascript’s quirky typeof:

typeof document.getElementsByTagName('p')

This will return 'function', which I did not expect. What is returned is a NodeList, which behaves like an array, identifies itself as a function, but really is neither.

If you want to detect a NodeList you’re better off with feature detection:

var isNodelist = (typeof myvar.length != 'undefined' &&
  typeof myvar.item != 'undefined')

Do note that this makes it probable you’re dealing with a NodeList – but you can’t be sure.

You cannot leave comments on my site, but you can always tweet questions or comments at me: @avdgaag.