DOM Node Type

Description

Every piece of markup can be represented by a node in the tree:

  • HTML elements are represented by element nodes
  • Attributes are represented by attribute nodes
  • Document type is represented by a document type node
  • Comments are represented by comment nodes

In total, there are 12 node types, all of which inherit from a base type.

DOM Level 1 has an interface called Node implemented by all node types in the DOM.

The Node interface is implemented in JavaScript as the Node type.

All node types inherit from Node in JavaScript, so all node types share the same basic properties and methods.

Every node has a nodeType property that indicates the type of node that it is. Node types are represented by one of the following 12 numeric constants on the Node type:

TypeValue
Node.ELEMENT_NODE1
Node.ATTRIBUTE_NODE2
Node.TEXT_NODE3
Node.CDATA_SECTION_NODE4
Node.ENTITY_REFERENCE_NODE5
Node.ENTITY_NODE6
Node.PROCESSING_INSTRUCTION_NODE7
Node.COMMENT_NODE8
Node.DOCUMENT_NODE9
Node.DOCUMENT_TYPE_NODE10
Node.DOCUMENT_FRAGMENT_NODE11
Node.NOTATION_NODE12

Node Type

A node's type is easy to determine by comparing against one of these constants:


<!DOCTYPE HTML> 
<html> 
<body> 
  <pre id="results"></pre> 
  <script> 
    var resultsElement = document.getElementById("results"); 
    document.writeln(resultsElement.nodeType); 
    document.writeln(resultsElement.nodeName); 
    if (resultsElement.nodeType == Node.ELEMENT_NODE){ 
       //won't work in IE < 9
       document.writeln("Node is an element."); 
    } <!--from  www  .java2s.  c  o  m-->
    if (resultsElement.nodeType == 1){//works for all
       document.writeln("Node is an element."); 
    } 
    
  </script> 
</body> 
</html>

Click to view the demo





















Home »
  Javascript »
    Javascript Introduction »




Script Element
Syntax
Data Type
Operator
Statement
Array
Primitive Wrapper Types
Function
Object-Oriented
Date
DOM
JSON
Regular Expressions