← back to all talks and articles

Javascript typeof Nodelist

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.

Arjan van der Gaag

Arjan van der Gaag

A thirtysomething software developer, historian and all-round geek. This is his blog about Ruby, Rails, Javascript, Git, CSS, software and the web. Back to all talks and articles?

Discuss

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