DOM Node Type Constants In JavaScript

When accessing the Document Object Model (DOM) through JavaScript, the nodeType field of a DOM node contains an integer corresponding to the type of the node. Using these ‘magic numbers’ in code is bad practice as it makes code less readable, so the Document Object Model Core defines twelve constants to use instead.

Unfortunately some browsers, including Internet Explorer, don’t implement this part of the DOM. However, this can be easily fixed, and the following JavaScript code provides these constants in browsers such as Internet Explorer:

if (!window.Node) var Node =
    {
      ELEMENT_NODE                :  1,
      ATTRIBUTE_NODE              :  2,
      TEXT_NODE                   :  3,
      CDATA_SECTION_NODE          :  4,
      ENTITY_REFERENCE_NODE       :  5,
      ENTITY_NODE                 :  6,
      PROCESSING_INSTRUCTION_NODE :  7,
      COMMENT_NODE                :  8,
      DOCUMENT_NODE               :  9,
      DOCUMENT_TYPE_NODE          : 10,
      DOCUMENT_FRAGMENT_NODE      : 11,
      NOTATION_NODE               : 12
    }

Achieving cross-browser support for JavaScript

Writing JavaScript that works with a range of browsers is not easy, as their implementations of the standard (ECMA-262) differ. The O’Reilly book JavaScript the Definitive Guide details which JavaScript features are supported by different browsers’ implementations, and is very helpful in writing code that works in a range of web browsers.

This article was last edited on 15th March 2008. The author can be contacted using the form below.