Javascript typeof Nodelist

05-02-2010
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.