DOM nodeType constants in JavaScript

The Document Object Model (DOM) allows JavaScript code to access and manipulate HTML documents through DOM nodes. DOM nodes can be of various types, such as element nodes and text nodes, and each node has a nodeType property giving its type. The DOM specification defines twelve constants corresponding to these types, which can be accessed through the Node object in compatible browsers.

Unfortunately Internet Explorer still does not provide this object, more than a decade after the DOM specification was released and despite two Microsoft employees being editors of the specification. The page provides a small piece of JavaScript that can be copied into your code to ensure these constants are available in all browsers.

The code

Copy the following code to your JavaScript, adding it before your first use of the constants.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
// create the nodeType constants if the Node object is not defined
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
      };
}

An example of using nodeType constants

The following code outputs any comments contained within the HTML source code of a page. It uses the nodeType constants to identify element nodes (in which it recursively searches) and comment nodes (whose content it outputs).

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
/* Outputs the contents of all comment nodes that are descendants of the
 * specified node. The parameter is:
 *
 * node - the node whose descendants should be searched
 */
function outputComments(node){

  // initialise the child node
  var child = node.firstChild;

  // loop while the child node exists
  while (child){

    // determine the type of the node
    switch (child.nodeType){

      // if the node is an element node, recurse into it
      case Node.ELEMENT_NODE : outputComments(child); break;

      // if the node is a comment node, output its value
      case Node.COMMENT_NODE : alert(child.nodeValue); break;

    }

    // move to the next child node
    child = child.nextSibling;

  }

}

// output the content of all comment nodes in the document
outputComments(document.body);

Where now?

Found this useful? Share it:

Recommended reading:

Professional JavaScript for Web Developers by Nicholas C. Zakas

Also in JavaScript: