tagName vs nodeName

tagName and nodeName are both useful Javascript properties for checking the name of an html element. For most purposes, either will do fine but nodeName is preferred if you are supporting only A-grade browsers and tagName is preferred if you intend to support IE5.5 as well.

There are two issues with tagName:

  • In all versions of IE, tagName returns ! when called on a comment node
  • For text nodes, tagName returns undefined where as nodeName returns #text

nodeName has it’s own set of issues but they are less severe:

  • IE 5.5 returns ! when called on a comment node. This is less harmful than tagName which suffers from this behaviour across all versions of IE
  • IE 5.5 doesn’t support nodeName for the document element or for attributes. Neither of these should be a concern for most practical purposes but should be kept in mind in any case
  • Konqueror ignores comment nodes when using this property. But then again, Konqueror, along with IE 5.5 is not an A-grade browser

So for most practical purposes stick to nodeName due to its support for a wider range of scenarios and potentially better forward compatibility. Not to mention that it doesn’t hiccup on a comment node, which has a tendency to creep into code unannounced. Don’t worry about IE 5.5 or Konqueror as their market share is near 0%.

2 Responses

This article is no longer open for comments